一个接口允许存在任意的属性
interface IPerson {
name: string;
age: number;
userBio?: string;
[propName: string]: any;
}
let wangzz: IPerson = {
name: 'wangzz',
age: 24,
userBio: '万事胜意',
gender: 'male' // 任意属性取string类型的值
}
一旦定义任意属性,确定属性和可选属性的类型都必须时其类型的子类型
interface Person {
name: string;
age?: number;
[propName: string]: string;
}
let tom: Person = {
name: 'Tom',
age: 25,
gender: 'male'
};
// index.ts(3,5): error TS2411: Property 'age' of type 'number' is not assignable to string index type 'string'.
// index.ts(7,5): error TS2322: Type '{ [x: string]: string | number; name: string; age: number; gender: string; }' is not assignable to type 'Person'.
// Index signatures are incompatible.
// Type 'string | number' is not assignable to type 'string'.
// Type 'number' is not assignable to type 'string'.
标签:TypeScript,string,age,number,接口,name,添加,type,属性 From: https://www.cnblogs.com/openmind-ink/p/17260047.html