Angular 的新手,我不明白这段代码:
export interface MyType {
[propertyName: string]: string | MyType;
}
我理解全局类型的作用是将其与我们应用程序的业务对象一起使用。类型允许捕获用户在函数中提供的类型。
但是上面的代码我看不懂:
感谢帮助
先是typescript不是angular
export interface MyType {
[propertyName: string]: string | MyType;
}
我认为最好使用 key
interface MyType {
[key: string]: string | MyType;
}
在你的例子中 [] 用于只能是字符串的键。不可能
let x : MyType = {1:"sss"}
Key 应该只是字符串,如
let x : MyType = {"1":"sss"}
[propertyName:string]
表示这个界面可以有零个或多个键,就像地图一样。如果你想表示一些子项或二叉树,为什么值可能再次是相同的数据类型。这是一个如何使用此接口的示例:
interface MyType {
[propertyName: string]: string | MyType;
}
const a : MyType = {foo: 'bar'}
const b : MyType = {key1: a, key2: 'bar', key3: 'three'}
const c : MyType = {a, b}
const bar: MyType = {
a,
b,
c,
}