jkchao / typescript-book-chinese

TypeScript Deep Dive 中文版
https://jkchao.github.io/typescript-book-chinese/
MIT License
6.53k stars 673 forks source link

问一个接口的问题 #156

Open bigGoodMan opened 4 years ago

bigGoodMan commented 4 years ago
 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 反而正确

only4s44u commented 4 years ago

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