Typescript 接口中变量属性的编译器错误
我不明白为什么编译器在函数test1中说,类型“ITest1”上不存在属性“name”和“姓氏”;我弄糊涂了……:Typescript 接口中变量属性的编译器错误,typescript,types,Typescript,Types,我不明白为什么编译器在函数test1中说,类型“ITest1”上不存在属性“name”和“姓氏”;我弄糊涂了……: interface ITest1{ name: string; surname: string; age: number; } interface ITest2{ city: string; nation: string; isEU: boolean; } //function test1<ITest1, ITest2&g
interface ITest1{
name: string;
surname: string;
age: number;
}
interface ITest2{
city: string;
nation: string;
isEU: boolean;
}
//function test1<ITest1, ITest2>(a:ITest1|ITest2): ITest1|ITest2{
function test1<ITest1, ITest2>(a:ITest1|ITest2): string{
return (a as ITest1).name +
(a as ITest1).surname;
}
let a : ITest1 = {
name:"",
surname:"",
age:0
};
a.name="John";
a.surname="Taylor";
a.age=30;
console.log(test1(a));
接口ITest1{
名称:字符串;
姓氏:弦;
年龄:人数;
}
接口ITest2{
城市:字符串;
国家:弦;
isEU:布尔型;
}
//功能测试1(a:ITest1 | ITest2):ITest1 | ITest2{
函数test1(a:ITest1 | ITest2):字符串{
返回(作为ITest1)。名称+
(a)姓氏;
}
设a:ITest1={
姓名:“,
姓:“,
年龄:0
};
a、 name=“John”;
a、 姓氏=“泰勒”;
a、 年龄=30岁;
log(test1(a));
您需要修复您的功能(尽管我不确定您想用
实现什么)。只需将其更改为:
function test1(a: ITest1 | ITest2): string {
return (a as ITest1).name + (a as ITest1).surname;
}
输出:
$ tsc index.ts && node index
$ JohnTaylor
编辑:
测试某个属性是否不同于ITest1
和ITest2
:
function test1(a: ITest1 | ITest2 ): string {
if ('name' in a) {
// a implements ITest1
return `${a.name} ${a.surname}`;
}
// a implements ITest2
return `${a.city} ${a.nation}`;
// Or just:
// return 'name' in a ? `${a.name} ${a.surname}` : `${a.city} ${a.nation}`;
}
...
console.log(test1(a));
console.log(test1({city: "Foo", nation: "Bar", isEU: false}));
结果:
John Taylor
Foo Bar
如果有人调用
test1({city:,nation:,isEU:false})
?为什么test1
接受ITest1 | ITest2
参数?当有人调用test1({city:,nation:,isEU:false})
?@jcalz很好,我希望这是正确的方法:)