如果你有这样的界面:
interface ISimpleObject {
foo: string;
bar?: any;
}
此接口仅用于编译时和代码提示/智能感知。接口用于提供一种严格且类型安全的方式,以一致的方式使用具有已定义签名的对象。
如果您有使用上面定义的interface 的函数:
function start(config: ISimpleObject):void {
}
如果对象没有ISimpleObject 接口的确切签名,TypeScript 编译将失败。
调用函数start有多种有效技术:
// matches the interface as there is a foo property
start({foo: 'hello'});
// Type assertion -- intellisense will "know" that this is an ISimpleObject
// but it's not necessary as shown above to assert the type
var x = <ISimpleObject> { foo: 'hello' };
start(x);
// the type was inferred by declaration of variable type
var x : ISimpleObject = { foo: 'hello' };
start(x);
// the signature matches ... intellisense won't treat the variable x
// as anything but an object with a property of foo.
var x = { foo: 'hello' };
start(x);
// and a class option:
class Simple implements ISimpleObject {
constructor (public foo: string, public bar?: any) {
// automatically creates properties for foo and bar
}
}
start(new Simple("hello"));
任何时候签名不匹配,编译都会失败:
// compile fail
var bad = { foobar: 'bad' };
start( bad );
// compile fail
var bad: ISimpleObject = { foobar: 'bad' };
// and so on.
没有“正确”的方法来做到这一点。这是风格选择的问题。如果它是一个被构造的对象(而不是直接作为参数传递),我通常会声明类型:
var config: ISimpleObject = { foo: 'hello' };
这样,代码完成/IntelliSense 将在我使用 config 变量的任何地方工作:
config.bar = { extra: '2014' };
TypeScript 中没有“强制转换”。它被称为类型断言,在此处描述的情况下不需要(我在上面提供了一个可以使用它的示例)。在这种情况下不需要声明变量 Type 然后使用断言(因为类型已经知道)。