类型声明适用于对象文字,但不适用于类实现

125*_*748 5 javascript types typescript

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

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]
}
Run Code Online (Sandbox Code Playgroud)

Property 'a' in type 'C' is not assignable to the same property in base type 'MyInterface'. Type 'number[]' is missing the following properties from type '[number, number]': 0, 1

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

[TypeScript游乐场]

sko*_*ovy 2

的类型a被推断为number[]不可分配给 tuple [number, number]。显式定义类型似乎ICoord有效a

type ICoord = [number, number];

type MyInterface = {
  a: ICoord;
}

class C implements MyInterface {
  a: ICoord = [0, 0];
}
Run Code Online (Sandbox Code Playgroud)

TypeScript 游乐场

  • 虽然确实如此,但我确信OP想知道为什么推理在对象文字中得到了正确的处理,而不是在类中得到了正确的处理。 (2认同)