如题。。。
interface A {
name: string;
}
怎样自动初始化 interface的对象。里面可能有任意属性。
比如本例的就是
const x:A = { name: ""}
如题。。。
interface A {
name: string;
}
怎样自动初始化 interface的对象。里面可能有任意属性。
比如本例的就是
const x:A = { name: ""}
interface 声明的时候是不能初始化的,因为所有 interface 在转成 JS 的时候都消失不见。要初始化有两个办法:
class AImpl implements A { ... }
function createA(): A { ... }
举例:
interface IPerson {
readonly name: string;
isMale: boolean;
age?: number;
}
class Person implements IPerson {
readonly name: string = "";
isMale: boolean = false;
age?: number;
}
function createPerson(): IPerson {
return {
name: "",
isMale: false,
};
}
打个广告,我的新课:TypeScript从入门到实践 【2020 版】