如何在 TypeScript 接口中定义静态属性

编程入门 行业动态 更新时间:2024-10-25 21:15:09
本文介绍了如何在 TypeScript 接口中定义静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只想在打字稿界面中声明一个静态属性?我没有找到任何关于此的地方.

I just want to declare a static property in typescript interface? I have not found anywhere regarding this.

interface myInterface { static Name:string; }

有可能吗?

推荐答案

你不能在 TypeScript 的接口上定义静态属性.

You can't define a static property on an interface in TypeScript.

假设您想更改 Date 对象,而不是尝试添加到 Date 的定义中,您可以包装它,或者简单地创建您的富日期类做Date 没有做的事情.

Say you wanted to change the Date object, rather than trying to add to the definitions of Date, you could wrap it, or simply create your rich date class to do the stuff that Date doesn't do.

class RichDate { public static MinValue = new Date(); }

因为 Date 是 TypeScript 中的一个接口,所以你不能使用 extends 关键字用一个类来扩展它,这有点遗憾,因为如果 date 是一个很好的解决方案班级.

Because Date is an interface in TypeScript, you can't extend it with a class using the extends keyword, which is a bit of a shame as this would be a good solution if date was a class.

如果您想扩展 Date 对象以在原型上提供 MinValue 属性,您可以:

If you want to extend the Date object to provide a MinValue property on the prototype, you can:

interface Date { MinValue: Date; } Date.prototype.MinValue = new Date(0);

调用使用:

var x = new Date(); console.log(x.MinValue);

如果你想让它在没有实例的情况下可用,你也可以......但有点麻烦.

And if you want to make it available without an instance, you also can... but it is a bit fussy.

interface DateStatic extends Date { MinValue: Date; } Date['MinValue'] = new Date(0);

调用使用:

var x: DateStatic = <any>Date; // We aren't using an instance console.log(x.MinValue);

更多推荐

如何在 TypeScript 接口中定义静态属性

本文发布于:2023-06-12 05:15:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/652009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   属性   接口   定义   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!