[英]Can a typescript var in an interface be declared of type A or B
We are setting up our class constructors to take an interface of the class for the copy constructor. 我们正在设置我们的类构造函数,使其采用该类的接口作为复制构造函数。 So basically:
所以基本上:
interface IPoint {
var x : number;
var y : number;
}
class Point implements IPoint {
var x : number;
var y : number;
constructor (src : IPoint) {
this.x = src.x;
this.y = src.y;
}
public getTotal() : number {
return x + y;
}
}
We do this because we get this objects as JSON from a REST server and also pass the objects to/from a web worker. 我们之所以这样做,是因为我们从REST服务器中以JSON形式获取了这些对象,并且还将这些对象传递给Web Worker或从Web Worker传递出去。 In these cases the object we receive is the interface, we have the data, but not the methods.
在这些情况下,我们收到的对象是接口,我们有数据,但没有方法。 The copy constructor works great for both the case of creating one from a full object as well as just the JSON.
对于从完整对象创建一个对象以及仅从JSON创建对象的情况,复制构造函数都非常有用。
But we hit a problem for the following case: 但是我们遇到了以下情况的问题:
interface IPoint {
var coordinates : (List or number[])
}
class Point implements IPoint {
var coordinates : List
constructor (src : IPoint) {
// do an isArray() to initialize
}
public getTotal() : number {
return // sum of all coordinates in the list
}
}
When we get the object from JSON, coordinates is an array. 当我们从JSON获取对象时,坐标是一个数组。 In the object it is a List (from collections.ts).
在对象中是一个列表(来自collections.ts)。
We're presently defining "coordinates : any" in the interface which does work. 我们目前正在有效的界面中定义“ coordinates:any”。 But it truly should always be one of two types.
但是它确实应该永远是两种类型之一。 Is there any way to declare it that way?
有什么办法可以这样声明吗? There's no difference at runtime doing this, but it does make for better type checking.
在运行时这样做没有什么区别,但是确实可以更好地进行类型检查。
我的建议是为坐标(列表或数字[])定义一个设置类型,并确保构造函数可以接受其中一个,然后将任何输入转换为所需的类型。
Well, assuming that List
supports the []
operator, you can do this: 好吧,假设
List
支持[]
运算符,则可以执行以下操作:
interface IIndexable<T> {
[index: number]: T
}
interface IPoint {
coordinates : IIndexable<number>
}
But it truly should always be one of two types.
但是它确实应该永远是两种类型之一。
Union types https://github.com/Microsoft/TypeScript/issues/14 are still to be implemented in typescript. 联合类型https://github.com/Microsoft/TypeScript/issues/14仍将在打字稿中实现。
You can use any
as you already know or you can use two variables with different types and assign appropriately. 您可以使用
any
已知的方法,也可以使用两个具有不同类型的变量并进行适当分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.