我想要一个类型来代表一个坐标。我已经应用到接口(interface)的类型适用于对象,但不适用于类。

type ICoord = [number, number]

type MyInterface = {
    a: ICoord
}

var obj: MyInterface = { // works
    a: [0, 0]
}

class C implements MyInterface { // gets below compilation error
    a = [0, 0]
}



为什么不能将[0, 0]分配给a

[TypeScript Playground]

最佳答案

a的类型被推断为number[],它不能分配给元组[number, number]。明确将类型定义为ICoorda似乎可行:

type ICoord = [number, number];

type MyInterface = {
  a: ICoord;
}

class C implements MyInterface {
  a: ICoord = [0, 0];
}

TypeScript Playground

08-18 18:22
查看更多