typescript-book-chinese icon indicating copy to clipboard operation
typescript-book-chinese copied to clipboard

问一个接口的问题

Open bigGoodMan opened this issue 5 years ago • 1 comments

 interface ObjINF1 {
    [key: string]: string | number | undefined;
}
interface ObjINF2 {
    id: number;
    title: string;
}
function a1(objArr: ObjINF1[]) {
    
}
function a2(objArr: ObjINF2[]) {
// Argument of type 'ObjINF2[]' is not assignable to parameter of type 'ObjINF1[]'.Type 'ObjINF2' is not assignable to type 'ObjINF1'. Index signature is missing in type 'ObjINF2'.
    a1(objArr) 
}

function a3(objArr: {
    id: number;
    title: string;
}[]) {
    a1(objArr) 
}

为什么a2报错了 a3 反而正确

bigGoodMan avatar Dec 30 '19 06:12 bigGoodMan

需要显式声明 interface ObjINF2 extends ObjINF1 {...} 才能保证 ObjINF2 类型可以赋值给 ObjINF1 类型,a3 是用字面量定义的所以没问题

only4s44u avatar Jan 15 '20 07:01 only4s44u