是的,将属性标记为可选非常容易,您可以在其后添加?:
class NavItem {
key: string;
text: string;
target: string;
children?: NavItem[];
}
或者,您也可以使用null 或undefined 的联合:
class NavItem {
key: string;
text: string;
target: string;
children: NavItem[] | undefined;
}
话虽如此,您误解了一些非常重要的事情,这是错误的:
const data: NavItem[] = [
{
key: "dashboard",
target: "dashboard",
text: "Dashboard",
children: []
},
{
key: "sales",
target: "sales",
text: "Sales"
}
];
data 是不是 NavItem 项目的数组,为了得到你需要使用new 关键字创建NavItem 的实例,例如:
const data: NavItem[] = [
Object.assign(new NavItem(), {
key: "dashboard",
target: "dashboard",
text: "Dashboard",
children: []
}),
Object.assign(new NavItem(), {
key: "sales",
target: "sales",
text: "Sales"
})
];
编译器不会抱怨这样做,因为 typescript 是 based on structural subtyping 并且这两种类型共享相同的结构。
但是给NavItem添加方法就很容易看出为什么不对了:
class NavItem {
key: string;
text: string;
target: string;
children?: NavItem[];
getKey() {
return this.key;
}
}
现在用你的代码试试这个:
console.log(data[0].getKey());
你最终会得到:
未捕获的类型错误:data[0].getKey 不是函数
您甚至应该得到一个编译错误,指出您的数组项中缺少getKey。
如果您只打算使用NavItem 作为数据对象,那么这并不重要,但您应该只使用接口或类型别名,因为它们不会被编译为 js,并且您可以避免多余的内存使用:
interface NavItem {
key: string;
text: string;
target: string;
children?: NavItem[];
}
编辑
在@Zze 发表评论后,我决定添加一个简单的构造函数,它使用Object.assign 的“力量”:
class NavItem {
key: string;
text: string;
target: string;
children?: NavItem[];
constructor(data?: NavItem) {
if (data) {
Object.assign(this, data);
}
}
}
然后:
new NavItem({
key: "sales",
target: "sales",
text: "Sales"
})