如何在 TypeScript 接口中定义静态属性 [英] How to define static property in TypeScript interface

查看:41
本文介绍了如何在 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 接口中定义静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆