我只是想在typescript接口中声明一个静态属性?我没有找到任何关于这方面的资料。

interface myInterface {
  static Name:string;
}

这可能吗?


在TypeScript中,你不能在接口上定义静态属性。

假设您想要更改Date对象,而不是尝试添加到Date的定义中,您可以包装它,或者简单地创建富Date类来完成Date没有完成的工作。

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

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

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

interface Date {
    MinValue: Date;
}

Date.prototype.MinValue = new Date(0);

使用:

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

如果你想让它在没有实例的情况下可用,你也可以…但这有点繁琐。

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);

静态属性通常放在对象的(全局)构造函数上,而“interface”关键字适用于对象的实例。

如果你用TypeScript编写类,前面给出的答案当然是正确的。如果你描述的是一个已经在其他地方实现的对象,那么包含静态属性的全局构造函数可以这样声明:

declare var myInterface : {
  new(): Interface;
  Name:string;
}

@duncan上面的解决方案为静态类型指定new()也适用于接口:

interface MyType {
    instanceMethod();
}

interface MyTypeStatic {
    new():MyType;
    staticMethod();
}

如果您正在寻找定义一个静态类(即。所有的方法/属性都是静态的),你可以这样做:

interface MyStaticClassInterface {
  foo():string;
}

var myStaticClass:MyStaticClassInterface = {
  foo() {
    return 'bar';
  }
};

在这种情况下,静态“类”实际上只是一个普通的-ol'-js-object,它实现了MyStaticClassInterface的所有方法


你可以正常定义接口:

interface MyInterface {
    Name:string;
}

但你不能这么做

class MyClass implements MyInterface {
    static Name:string; // typescript won't care about this field
    Name:string;         // and demand this one instead
}

为了表示一个类应该遵循这个接口来获取它的静态属性,你需要一点技巧:

var MyClass: MyInterface;
MyClass = class {
    static Name:string; // if the class doesn't have that field it won't compile
}

你甚至可以保留类名,TypeScript(2.0)不会介意:

var MyClass: MyInterface;
MyClass = class MyClass {
    static Name:string; // if the class doesn't have that field it won't compile
}

如果你想静态地继承许多接口,你必须首先将它们合并到一个新的接口中:

interface NameInterface {
    Name:string;
}
interface AddressInterface {
    Address:string;
}
interface NameAndAddressInterface extends NameInterface, AddressInterface { }
var MyClass: NameAndAddressInterface;
MyClass = class MyClass {
    static Name:string; // if the class doesn't have that static field code won't compile
    static Address:string; // if the class doesn't have that static field code won't compile
}

或者如果你不想命名合并接口,你可以这样做:

interface NameInterface {
    Name:string;
}
interface AddressInterface {
    Address:string;
}
var MyClass: NameInterface & AddressInterface;
MyClass = class MyClass {
    static Name:string; // if the class doesn't have that static field code won't compile
    static Address:string; // if the class doesn't have that static field code won't compile
}

工作示例


可以使用相同的名称将接口和命名空间合并:

interface myInterface { }

namespace myInterface {
  Name:string;
}

但是这个接口只有知道它的属性Name才有用。你不能实现它。


遵循@Duncan的@Bartvds的回答,在这里提供了一个可行的方法。

在Typescript 1.5发布后(@Jun 15 '15),你的有用界面

interface MyType {
    instanceMethod();
}

interface MyTypeStatic {
    new():MyType;
    staticMethod();
}

可以在decorator的帮助下以这种方式实现。

/* class decorator */
function staticImplements<T>() {
    return <U extends T>(constructor: U) => {constructor};
}

@staticImplements<MyTypeStatic>()   /* this statement implements both normal interface & static interface */
class MyTypeClass { /* implements MyType { */ /* so this become optional not required */
    public static staticMethod() {}
    instanceMethod() {}
}

参考我在github issue 13462的评论。

视觉效果: 编译错误,提示缺少静态方法。

静态方法实现后,提示方法缺失。

在静态接口和正常接口完成后进行编译。


我为我的特定用例找到了这样做的方法(不需要装饰器)。

检查静态成员的重要部分是IObjectClass,并在createObject方法中使用cls: IObjectClass<T>:

//------------------------
// Library
//------------------------
interface IObject {
  id: number;
}
interface IObjectClass<T> {
  new(): T;
  table_name: string;
}
function createObject<T extends IObject>(cls: IObjectClass<T>, data:Partial<T>):T {
  let obj:T = (<any>Object).assign({},
    data,
    {
      id: 1,
      table_name: cls.table_name,
    }
  )
  return obj;
}

//------------------------
// Implementation
//------------------------
export class User implements IObject {
  static table_name: string = 'user';
  id: number;
  name: string;
}

//------------------------
// Application
//------------------------
let user = createObject(User, {name: 'Jimmy'});
console.log(user.name);

是的,这是可能的。这是解决方案

export interface Foo {

    test(): void;
}

export namespace Foo {

    export function statMethod(): void {
        console.log(2);
    }

}

静态修饰符不能出现在类型成员上(TypeScript错误TS1070)。这就是为什么我建议使用抽象类和继承来解决任务:

例子

// Interface definition
abstract class MyInterface {
  static MyName: string;
  abstract getText(): string;
}

// Interface implementation
class MyClass extends MyInterface {
  static MyName = 'TestName';
  getText(): string {
    return `This is my name static name "${MyClass.MyName}".`;
  }
}

// Test run
const test: MyInterface = new MyClass();
console.log(test.getText());

虽然静态关键字不支持接口在Typescript 但我们可以通过创建一个具有静态成员的函数接口来实现。

在下面的代码中,我创建了一个函数接口Factory,它有两个静态成员serialNumber和printSerial。

// factory is a function interface
interface Factory<T> {
    (name: string, age: number): T;

    //staic property
    serialNumber: number;

    //static method
    printSrial: () => void;
}

class Dog {
    constructor(public name: string, public age: number) { }
}

const dogFactory: Factory<Dog> = (name, age) => {
    return new Dog(name, age);
}

// initialising static members

dogFactory.serialNumber = 1234;
dogFactory.printSrial = () => console.log(dogFactory.serialNumber);


//instance of Dog that DogFactory creates
const myDog = dogFactory("spike", 3);

//static property that returns 1234
console.log(dogFactory.serialNumber)

//static method that prints the serial 1234
dogFactory.printSrial();

这里没有提到的另一个选项是用表示静态接口的类型定义变量,并为其分配类表达式:

interface MyType {
    instanceMethod(): void;
}

interface MyTypeStatic {
    new(): MyType;
    staticMethod(): void;
}

// ok
const MyTypeClass: MyTypeStatic = class MyTypeClass {
    public static staticMethod() { }
    instanceMethod() { }
}

// error: 'instanceMethod' is missing
const MyTypeClass1: MyTypeStatic = class MyTypeClass {
    public static staticMethod() { }
}

// error: 'staticMethod' is missing
const MyTypeClass2: MyTypeStatic = class MyTypeClass {
    instanceMethod() { }
}

效果与使用装饰器的应答相同,但没有装饰器的开销

操场上

GitHub上的相关建议/讨论


我执行了一个类似Kamil sot的解决方案,但却产生了意想不到的效果。我没有足够的声誉来发表这条评论,所以我把它贴在这里,以防有人正在尝试这个解决方案并阅读这篇文章。

解决方案是:

interface MyInterface {
    Name: string;
}

const MyClass = class {
    static Name: string;
};

但是,使用类表达式不允许我使用MyClass作为类型。如果我这样写:

const myInstance: MyClass;

myInstance的类型是any,我的编辑器显示以下错误:

'MyClass' refers to a value, but is being used as a type here. Did you mean 'typeof MyClass'?ts(2749)

我最终失去了一个比我想通过类的静态部分的接口实现的更重要的类型。

瓦尔使用装饰器的解决方案避免了这个陷阱。


其他解决方案似乎偏离了正确的路径,我发现我的场景在Typescript文档中有覆盖,我在下面解释:

interface AppPackageCheck<T> {
  new (packageExists: boolean): T
  checkIfPackageExists(): boolean;
}

class WebApp {
    public static checkIfPackageExists(): boolean {
        return false;
    }

    constructor(public packageExists: boolean) {}
}

class BackendApp {
    constructor(public packageExists: boolean) {}
}

function createApp<T>(type: AppPackageCheck<T>): T {
    const packageExists = type.checkIfPackageExists();
    return new type(packageExists)
}

let web = createApp(WebApp);

// compiler failure here, missing checkIfPackageExists
let backend = createApp(BackendApp); 

我有点惊讶于上面的答案是多么的复杂!但也许这只是因为这个帖子太老了。

编辑:实际上,在经过一些测试后,我最初的尝试被证明是无用的,而且这个问题比我最初预期的要更难解决。

After about an hour or so of tinkering however, I think I may have just found the best/cleanest solution so far (building upon my initial idea)! If the question posed is "How do I include static properties in an interface?", then I think this is a fairly decent answer. This is at least better than extending a class if all you need is an interface (compiletime typing/requirements/restraints). There's no real drawback (well, maybe one small one) to this either since the solution is 100% ambient (unlike extends-based class extension like some answers are suggesting) and classes are constants regardless (immutable references that are not hoisted when using the standard class declaration syntax instead of a class expression as I'm doing here). This incurs no runtime overhead and doesn't require runtime class inheritance. You can define the entire class (both static and non-static members) all in one (ambient class used as an) interface!

以下是如何做到这一点!

/** ./interface.ts */
// In a file module (best), or wrap in ts module or namespace block

// Putting this in a module provides encapsulation ensuring that no one is
// at risk of misusing this class (it must be used as a type only). 

// Export only a type reference which will make it error is someone tries 
// to use it as a value (such as in an `extends` clause, or trying to 
// instantiate it).

/** 
 * Other Ideas For Names To Differentiate From Actual Classes/Non-Ambient Values:
 * MyClassInterface or _Interface_MyClass or MyClass_Interface or Interface_MyClass  
 **/
declare class _MyClassInterface {
    static staticProp: string;
    static staticMethod(): number;
    readonly prop: boolean 
    /** 
     * Note: Above, readonly won't need to be specified in the real class 
     * but the prop *will* still be readonly anyway.
     *
     * Now for the only caveat!
     * It does appear however that you cannot mark anything private or 
     * protected in this pseudo-interface which is a bummer, only props
     * and methods that appear only in the real class can be.
     */
    prop2: boolean;
    method(): Function;
    constructor(p1: string, p2: number);
}

export type MyClassInterface = typeof _MyClassInterface;

现在使用接口

/** ./consumer.ts */
import { MyClassInterface } from "./interface" // type import

const MyClass: MyClassInterface = class {
    static staticProp: string;
    prop: boolean;
    prop2: boolean;
    protected onlyOnRealClass: boolean; /* this is ok since this prop doesn't exist on the interface */

    static staticMethod() {
        return 5;
    }

    method() {
        return () => {};
    }

    constructor(p1: string, p2: number) {}
};

注意,typeof关键字在这里是绝对必要的(如果我没记错的话,这是因为如果没有它,typescript会认为我们在指定实例类型,而我们真正想要的是类本身的类型)。比如当我们这样做的时候

const a: MyClass = new MyClass()

没有typeof关键字,我们说a应该是MyClass的一个实例,而不是MyClass本身。

抽象确保你不会意外地尝试实例化类…

Edit: Actually I'm removing the abstract keyword from my answer because it turns out that the real class actually inherits the property of being abstract from the ambient class (makes sense), and will therefore not instantiate w/o the compiler complaining if the ambient class that provides its type is marked abstract... just gonna have to deal with ts not erroring if the ambient class is ever accidentally instantiated. It might be a decent idea then to prefix the ambient class declaration/name with an underscore and/or include the word Interface in the name so its proper use is clear (edit: I have since tackled this issue by encapsulating the interface in a file module thereby rendering it private to all other code and then exporting only a type reference to it).

这就是它的全部!

将接口放入模块中并不是完全必要的,但它提供了一些小好处,包括:

在整个实现代码中使用的“公开的”广泛使用的类型注释变得稍微小了一些,因为它不再包含关键字typeof 与包装的环境类/接口声明不同,导出/向外标识符严格来说是一种类型(别名),因此如果有人试图实例化它或在extends子句中使用它(或在其他需要运行时值的地方使用它),就会发生错误。

I'm not supplying a class name for the Class Expression in this example because Class Expressions, like all Function Expressions, will just inherit the identifier that they are assigned to if a class name if not provided. So if your identifier is identical to the name you want for that class or function anyways, you can just leave it off. Or, you may provide one inline as usual and it will take precedence over the identifier. A class or function name can also be changed after function/class creation, but only via Object.defineProperty or Object.defineProperties.

FWIW类实际上可以由另一个类实现(至少在TS的最新版本中),但静态属性将被忽略。似乎实现任何东西都只适用于原型的两个方向(到/从)。


这里有一个相当简单的方法:

interface MyClass {
    new (): MyClassInstance;
    staticMethod(): string;
}

interface MyClassInstance {
    instanceMethod(): string;
}

const Class: MyClass = class {
    static staticMethod() {
        return "This is a static method";
    }
    instanceMethod() {
        return "This is an instance method";
    }
}

Class.staticMethod();

// Has type MyClassInstance
const instance = new Class();
instance.instanceMethod();

请注意,这并不允许您像通常那样让类扩展接口,但对于许多情况来说,这已经足够好了。


解决方案

返回I的实例类型,并确保C扩展I:

type StaticImplements<I extends new (...args: any[]) => any, C extends I> = InstanceType<I>;

实例方法接口:

interface MyInstance {
    instanceMethod();
}

接口采用静态方法:

interface MyClassStatic {
    new (...args: any[]): MyInstance;
    staticMethod();
}

类需要静态方法并使用自己的方法进行扩展:

class MyClass implements StaticImplements<MyClassStatic, typeof MyClass> {
    static staticMethod();
    static ownStaticMethod();
    instanceMethod();
    ownInstanceMethod();
}

推理

在接口中定义静态方法将在#33892中讨论,抽象静态方法将在#34516中讨论。

基于Val和Aleksey的回答(谢谢),这个解决方案:

不需要额外的运行时值 保留类自身的成员信息 允许构造函数约束

Test

原样-游乐场连结:

MyClass.staticMethod(); // OK
MyClass.ownStaticMethod(); // OK
new MyClass().instanceMethod(); // OK
new MyClass().ownInstanceMethod(); // OK

如果从MyClass - Playground中删除staticMethod:

class MyClass implements StaticImplements<MyClassStatic, typeof MyClass> {} // Type 'typeof MyClass' does not satisfy the constraint 'MyClassStatic'. Property 'staticMethod' is missing in type 'typeof MyClass' but required in type 'MyClassStatic'.

如果从MyClass - Playground中删除instanceMethod:

class MyClass implements StaticImplements<MyClassStatic, typeof MyClass> {} // Class 'MyClass' incorrectly implements interface 'MyInstance'. Property 'instanceMethod' is missing in type 'MyClass' but required in type 'MyInstance'.

简单的例子

interface Person {
  name: string;
  age: number;
}

abstract class Trackable {
  static TrackInstances: number;
}

class Pablo extends Trackable implements Person {
  constructor(public name: string, public age: number) { Pablo.TrackInstances+=1; }
}
console.log(Pablo.TrackInstances);

我的解决方案对于添加额外静态构造函数的用例非常有效。我已经测试过了,它通过了所有的测试。如果有人发现有问题,请告诉我。

我做了一个泛型类型,它接受接口和静态接口。

它适用于具体类和抽象类。

我使用条件类型来设计它,这样所有的错误都可以传播 到实现接口的类,而不是接口本身。

注意:错误传播允许vscode快速修复(实现所有方法)。唯一的缺点是你必须自己应用static关键字,因为没有快速修复这个错误的方法。

的接口:

type Class<T = any> = new (...args: any[]) => T;
type AbstractClass<T = any> = abstract new (...args: any[]) => T;

type Interface<C extends Class<InstanceType<C>> | AbstractClass<InstanceType<C>>, SI, I = {}> = 
    C extends Class<InstanceType<C>> 
    // ConcreteClass
    ? InstanceType<C> extends I 
        ? C extends (SI & Class<InstanceType<C>>)
            ? (InstanceType<C> & I)
            : (SI & Class<InstanceType<C>>) // Indicate StaticInterface Error
        : I // Indicate Interface Error
    // AbstractClass
    : InstanceType<C> extends I 
        ? C extends (SI & AbstractClass<InstanceType<C>>)
            ? (InstanceType<C> & I)
            : (SI & AbstractClass<InstanceType<C>>) // Indicate StaticInterface Error
        : I // Indicate Interface Error

用法:

interface MyInterface {
    instanceMethod(): number;
}

interface MyStaticInterface {
    staticMethod(): number;
}
 
class MyClass implements Interface<typeof MyClass, MyStaticInterface, MyInterface> {
    static staticMethod(): number {
        return 50;
    }

    instanceMethod(): number {
        return 100;
    }

    static otherStatic() {
        return "HELLO"
    }

    otherInstance() {
        return "GOODBYE"
    }
}

abstract class MyClass1 implements Interface<typeof MyClass1, MyStaticInterface, MyInterface> {
    static staticMethod(): number {
        return 50;
    }


    instanceMethod(): number {
        return 20;
    }

    static otherStatic() {
        return "HELLO"
    }

    otherInstance() {
        return "GOODBYE"
    }

    abstract abstractMethod() : number;

}

温特特拉特给出了一个很好的答案,让我走上了正确的轨道。 然而,强制在静态接口中包含构造函数是非常不方便的。

简化版本

反转extends函数得到:

type Static<TClass extends IStaticInterface & { new(...args) }, IStaticInterface>
  = InstanceType<TClass>;

不需要为接口添加构造函数:

interface IMeow { readonly IsMeow: boolean; }

并像这样方便地使用:

class Cat implements Static<typeof Cat, IMeow> {
  readonly static IsMeow = true;
}

就像之前一样,如果Cat中缺少静态的IsMeow,它会给出一个非常明确的错误。 也像以前一样,它在其他方面仍然正常工作。

奇特的可读性(主观)

在类型后面需要一个"implements"字符串:

type Static<TClass extends IStaticInterface & { new(...args) },
  _txt extends "implements", IStaticInterface>
  = InstanceType<TClass>;

这里再次演示我们的猫:

class Cat implements Static<typeof Cat, "implements", IMeow> {
  static readonly IsMeow = true;
}

合并多个(过多)

这真的不需要,你只需要重复Static<…>,但下面是:

type Static<TClass extends InterfacesCombined & { new(...args) }, _txt extends "implements",
  IStaticInterface, IStatic2 = {}, IStatic3 = {}, IStatic4 = {}, IStatic5 = {},
  InterfacesCombined extends IStaticInterface & IStatic2 & IStatic3 & IStatic4 & IStatic5
    = IStaticInterface & IStatic2 & IStatic3 & IStatic4 & IStatic5>
  = InstanceType<TClass>;

为了演示让我们升级我们的猫更复杂:

interface IPurr { purr(): string; }
interface ILick { Lick(human: any): void; }

用法如下:

class Cat implements IPurr, Static<typeof Cat, "implements", IMeow, ILick> {
  static readonly IsMeow = true;
  static Lick(human: any) { /* obey me homan! */ }
  
  purr() { return "Prrrrr"; }
}

一个具体的静态接口

如果你经常使用静态接口,你不会想要键入所有的静态<…的东西。 首先让我们先把这个小帮手弄走:

type New<T> = { new(...args: any): T };

现在让我们“烘焙”一个静态的ILick接口:

type IStaticLick<TClass extends ILick & New<InstanceType<TClass>> = InstanceType<TClass>;

瞧:

class Cat2 implements IStaticLick<typeof Cat2> {
  static Lick(human: any) { /* obey me homan! */ }
}

到底发生了什么?

我们只是要求typeof T实现一些东西,使其成为“静态接口”的有效参数。

所以如果接口IFoo {stuff} +类Foo实现IFoo说Foo是“stuff”,那么我们所说的是“stuff”必须在T中,因为T被允许在Static<T中,…>。

所以类Foo的implements部分实现了Static<…>并没有真正说明Foo有什么特殊的东西。更确切地说,我们只是说我们有这些花哨的<括号>,里面是一个只接受“东西”滚轮的VIP俱乐部!

换句话说,我们可以写成:

class FakeCat implements IStaticLick<typeof Cat2> { }

...明白我的意思了吧?

我们试图通过要求静态<TClass,…来减少这个明显的问题。>实际实现TClass的实例类型。但是,如果InstanceType<TClass>没有任何实例成员(例如我们的Cat2类),则此方法将不起任何作用。

FakeCat确实实现了Cat2 -因为它不是很难实现:{}。

Demo

操场上的链接