I have a simple class
Board
width
height
types
number
types
types
<T>
T
this.types
Type 'number[]' is not assignable to Type 'T[]' Type 'number' is not assignable to Type 'T'
export class Board<T> {
constructor(width: number = 8, height: number = 8, types: T[] = [0, 1, 2, 3, 4, 5, 6]) {
this.width = width;
this.height = height;
this.types = types;
}
getTypes(): T[] {
return this.types;
}
}
T
this.types
new Board(8, 8, ['a', 'b', 'c', 'd']);
T
string
new Board()
T
number
Better approach using advanced types:
class Board<T> {
private width:number;
private height:number;
private types:T[]|number[];
constructor(width:number = 8, height:number = 8, types:T[]|number[] = [1, 2]) {
this.width = width;
this.height = height;
this.types = types;
}
getTypes():T[]|number[] {
return this.types;
}
}
https://jsfiddle.net/r8uqn760/2/
Old answer using type alias:
This approach will always allow numbers in the this.types array.
For example new Board(0, 0, [0, "foo"])
will pass at compilation, and I think it's not what you want to happen.
type X<Y> = number | Y;
class Board<T> {
private width:number;
private height:number;
private types:X<T>[];
constructor(width:number = 8, height:number = 8, types = [1,2] as X<T>[]) {
this.width = width;
this.height = height;
this.types = types;
}
getTypes():X<T>[] {
return this.types;
}
}