typescript-tutorial icon indicating copy to clipboard operation
typescript-tutorial copied to clipboard

对象的类型——接口-->任意属性 示例代码 报错

Open cccnoob opened this issue 5 years ago • 1 comments
trafficstars

对象的类型——接口-->任意属性

一个接口中只能定义一个任意属性。如果接口中有多个类型的属性,则可以在任意属性中使用联合类型:

interface Person {
    name: string;
    age?: number; 
    [propName: string]: string | number;
}
let tom: Person = {
    name: 'Tom',
    age: 25,
    gender: 'male'
};

// error TS2411: Property 'age' of type 'number | undefined' is not assignable to string index type 'string | number'

cccnoob avatar Apr 27 '20 06:04 cccnoob

确实,这里的age不能是可选的

mengliren666 avatar Jun 20 '22 09:06 mengliren666