Types 重载构造函数时的类型问题
我在重载构造函数时遇到问题,它不会让我告诉它变量包含什么类型。我怎样才能强制一个类型,或使它无论如何工作Types 重载构造函数时的类型问题,types,typescript,Types,Typescript,我在重载构造函数时遇到问题,它不会让我告诉它变量包含什么类型。我怎样才能强制一个类型,或使它无论如何工作 constructor(points: Point[], name?: string); constructor(walls: Wall[], name?: string); constructor(pointsOrWalls: (Wall | Point)[], name?: string) { if (pointsOrWalls[0] instanceof Point) {
constructor(points: Point[], name?: string);
constructor(walls: Wall[], name?: string);
constructor(pointsOrWalls: (Wall | Point)[], name?: string) {
if (pointsOrWalls[0] instanceof Point) {
// If first is Point all must be Points
// But here typescript says that pointsOrWalls is of type (Wall | Point)[]
this.walls = pointsOrWalls.map(function(point, ind, points) {
return new Wall(point, points[++ind % points.length])
})
}else{
// Since these aren't points they are Walls
this.walls = walls
}
this.name = name
}
我怎样才能强制一个类型,或者让这个工作无论如何
使用类型断言:
// If first is Point all must be Points
let points = pointsOrWalls as Point[];
完成:
class Wall {w}
class Point {p}
class Foo {
walls;
name
constructor(points: Point[], name?: string);
constructor(walls: Wall[], name?: string);
constructor(pointsOrWalls: (Wall | Point)[], name?: string) {
if (pointsOrWalls[0] instanceof Point) {
// If first is Point all must be Points
let points = pointsOrWalls as Point[];
// But here typescript says that pointsOrWalls is of type (Wall | Point)[]
this.walls = points.map(function(point, ind, points) {
return new Wall(point, points[++ind % points.length])
})
}else{
// Since these aren't points they are Walls
this.walls = walls
}
this.name = name
}
}
更多
我怎样才能强制一个类型,或者让这个工作无论如何
使用类型断言:
// If first is Point all must be Points
let points = pointsOrWalls as Point[];
完成:
class Wall {w}
class Point {p}
class Foo {
walls;
name
constructor(points: Point[], name?: string);
constructor(walls: Wall[], name?: string);
constructor(pointsOrWalls: (Wall | Point)[], name?: string) {
if (pointsOrWalls[0] instanceof Point) {
// If first is Point all must be Points
let points = pointsOrWalls as Point[];
// But here typescript says that pointsOrWalls is of type (Wall | Point)[]
this.walls = points.map(function(point, ind, points) {
return new Wall(point, points[++ind % points.length])
})
}else{
// Since these aren't points they are Walls
this.walls = walls
}
this.name = name
}
}
更多
虽然这很好,但有没有办法不重新声明变量?你可以创建一个用户定义的类型guardDon不明白,什么guard?@Akxe我刚刚为你写了文档:非常感谢,这绝对值得加入书签尽管这很好,有没有办法不重新声明变量?你可以创建一个用户定义的类型guardDon不明白,什么guard?@Akxe我刚刚为你写了文档:非常感谢,这绝对值得放在书签里