Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type declaration works for object literal, but not for class implementation

I want a type to represent a coordinate. The type I have have applied to an interface works for an object but not a class.

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]
}

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

Why can't I assign [0, 0] to a?

[TypeScript Playground]

like image 708
1252748 Avatar asked Oct 16 '22 11:10

1252748


1 Answers

The type of a is being inferred as number[] which is not assignable to the tuple [number, number]. Explicitly defining the type as ICoord for a appears to work:

type ICoord = [number, number];

type MyInterface = {
  a: ICoord;
}

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

TypeScript Playground

like image 89
skovy Avatar answered Oct 19 '22 01:10

skovy