打字的打字稿
问题描述:
我有功能与参数命名PARAM这样的:打字的打字稿
function x(param: One | Two) {
//do something
}
interface One {
value: IValue,
name: string,
id: number
}
interface Two {
value: IValue2,
name: string,
id: number,
selected: boolean
}
我可以使用相同的参数,两个不同的接口?谢谢!
答
你可以,你的参数语法正确!作为参考,TypeScript将其称为union type。
主要告诫使用它们的是,你只能访问成员共同所有的类型 - 例如,你都含有接口name
,value
和id
,这样你就可以在你的函数中使用这些。但是,只有interfaceTwo
拥有selected
成员,因此无法使用。另外,我不知道这个例子是否是您刚刚输入的内容,因此您可能已经知道这一点,但是您的接口定义不正确 - 您需要使用关键字interface
用分号结尾。这也是一个惯例给类型TitleCase
名称:
function x(param: InterfaceOne | InterfaceTwo){
console.log(param.name); // Valid!
console.log(param.id); // Valid!
console.log(param.value); // Valid - but has the type IValue | IValue2,
// so you can only access the common fields
// of those types!
console.log(param.selected); // INVALID - InterfaceOne doesn't have a selected member
}
interface InterfaceOne {
value: IValue;
name: string;
id: number;
}
interface InterfaceTwo {
value: IValue2;
name: string;
id: number;
selected: boolean;
}
如果在某些时候,你会想用param.selected属性,你可以定义和使用类型保护功能:功能isInterfaceTwo(PARAM):参数是InterfaceTwo {...}。更多关于[这里](https://blogs.msdn.microsoft.com/typescript/2015/09/16/announcing-typescript-1-6/) – baryo
@baryo:是的,我真的没有资格详细介绍保镖类型,因为我从来没有使用过它们,但他们肯定听起来像是可以在这种情况下有所帮助! –