我刚刚开始使用 TypeScript,我想知道如何为这种类型的对象声明接口(interface):
const branch = {
'CN': {
'name': 'CN Name',
'branch': 'Chinoise',
'url': 'CN URL'
},
'DE': {
'name': 'DE Name',
'branch': 'Allemande',
'discord': 'DE Discord',
'url': 'DE URL'
},
'EN': {
'name': 'EN Name',
'branch': 'Anglaise',
'url': 'EN URL'
},
[...]
}
如你所见,我有这个界面:
interface Branch {
name: string,
branch: string,
discord?: string,
url: string
}
上面的代码重复了几次。 所以我想知道是否可以对 TypeScript 说:“嘿,Branch 对象包含这个重复多次的接口(interface)”。
谢谢!
最佳答案
你可以这样做:
const branch: {[key: string]: Branch} = ...;
这意味着branch变量是一个对象,其键是字符串类型,值是Branch
类型;
索引签名官方文档:https://www.typescriptlang.org/docs/handbook/interfaces.html
关于javascript - typescript 对象模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951298/