如果你有一个像这样的界面:
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.
没有"正确"的方法来做这件事.这是风格 Select 的问题.如果它是构造的对象(而不是直接作为参数传递),我通常会声明类型:
var config: ISimpleObject = { foo: 'hello' };
这样,代码完成/智能感知将在我使用config
变量的任何地方工作:
config.bar = { extra: '2014' };
打字脚本中没有"铸造".它被称为类型断言,在这里描述的情况下不应该需要它(我在上面提供了一个可以使用它的示例).在本例中,不需要声明变量类型,然后使用断言(因为类型已经已知).