interfacePerson { name:string; age:number;}let tom:Person= { name:'Tom'};// index.ts(6,5): error TS2322: Type '{ name: string; }' is not assignable to type 'Person'.// Property 'age' is missing in type '{ name: string; }'.
多一些屬性也是不允許的:
interfacePerson { name:string; age:number;}let tom:Person= { name:'Tom', age:25, gender:'male'};// index.ts(9,5): error TS2322: Type '{ name: string; age: number; gender: string; }' is not assignable to type 'Person'.
// Object literal may only specify known properties, and 'gender' does not exist in type 'Person'.
interfacePerson { name:string; age?:number;}let tom:Person= { name:'Tom', age:25, gender:'male'};// examples/playground/index.ts(9,5): error TS2322: Type '{ name: string; age: number; gender: string; }' is not assignable to type 'Person'.
// Object literal may only specify known properties, and 'gender' does not exist in type 'Person'.
interfacePerson { 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'.
上例中,任意屬性的值允許是 string,但是可選屬性 age 的值卻是 number,number 不是 string 的子屬性,所以報錯了。
interfacePerson {readonly id:number; name:string; age?:number; [propName:string]:any;}let tom:Person= { id:89757, name:'Tom', gender:'male'};tom.id =9527;// index.ts(14,5): error TS2540: Cannot assign to 'id' because it is a constant or a read-only property.
上例中,使用 readonly 定義的屬性 id 初始化後,又被賦值了,所以報錯了。
注意:唯讀的約束存在於第一次給「物件」賦值的時候,而不是第一次給「唯讀屬性」賦值的時候:
interfacePerson {readonly id:number; name:string; age?:number; [propName:string]:any;}let tom:Person= { name:'Tom', gender:'male'};tom.id =89757;// index.ts(8,5): error TS2322: Type '{ name: string; gender: string; }' is not assignable to type 'Person'.// Property 'id' is missing in type '{ name: string; gender: string; }'.// index.ts(13,5): error TS2540: Cannot assign to 'id' because it is a constant or a read-only property.