我有一个代码:
// Library interfaces
interface PersonalData {
name: string;
age: number;
nick: string;
friends?: Friends[];
}
interface Friends extends PersonalData { }
// I want to add new props girls in friend interface
interface NewPropGirl {
girl: string;
friends?: NewPops[];
}
interface NewPops extends NewPropGirl { }
const test = (): Friends[] & NewPops[] => {
return [{
name: 'Oleg',
age: 25,
nick: 'yyy',
girl: 'Test',
friends: [{
name: 'Roman',
age: 22,
nick: 'bob',
girl: 'Test',
}]
}];
}
我想向库界面添加一个新的界面参数 girl 。在这段代码中,我在第31行有一个错误
TYPESCRIPT版本3.5.3
Type '{ name: string; age: number; nick: string; girl: string; friends: { girl: string; }[]; }[]' is not assignable to type 'Friends[] & NewPops[]'.
Type '{ name: string; age: number; nick: string; girl: string; friends: { girl: string; }[]; }[]' is not assignable to type 'Friends[]'.
Type '{ name: string; age: number; nick: string; girl: string; friends: { girl: string; }[]; }' is not assignable to type 'Friends'.
Object literal may only specify known properties, and 'girl' does not exist in type 'Friends'.
游乐场链接:playground
答案 0 :(得分:2)
我已将PersonalData扩展到NewPropGirl,以使您的结果包含一个额外的字段,并将其作为返回类型
interface PersonalData {
name: string;
age: number;
nick: string;
friends ? : Friends[];
}
interface Friends extends PersonalData {}
// I want to add new props
interface NewPropGirl extends PersonalData {
girl: string;
friends ? : NewPops[];
}
interface NewPops extends NewPropGirl {}
const test = (): NewPops[] => {
return [{
name: 'Oleg',
age: 25,
nick: 'yyy',
girl: 'Test',
friends: [{
name: 'Roman',
age: 22,
nick: 'bob',
girl: 'Test',
}]
}];
}
答案 1 :(得分:0)
interface PersonalData {
name: string;
age: number;
nick: string;
friends?: Friends[];
}
interface Friends extends PersonalData { }
// I want to add new props
interface NewPropGirl extends PersonalData {
girl: string;
friends?: NewPops[];
}
interface NewPops extends NewPropGirl { }
const test = (): Friends[] | NewPops[] => {
return [{
name: 'Oleg',
age: 25,
nick: 'yyy',
girl: 'Test',
friends: [{
name: 'Roman',
age: 22,
nick: 'bob',
girl:"Bella"
}]
}];
}
查看它是否符合您的需求。 Playground