【发布时间】:2021-01-09 12:58:09
【问题描述】:
如何在 TypeScript 中为具有任何属性的对象定义接口?
interface Data {
properties: Properties;
}
interface Properties {
...
}
【问题讨论】:
标签: typescript interface properties
如何在 TypeScript 中为具有任何属性的对象定义接口?
interface Data {
properties: Properties;
}
interface Properties {
...
}
【问题讨论】:
标签: typescript interface properties
具有任何属性的对象就像any。为什么要定义一个额外的接口?
一个原因可能是,您希望允许特定的值类型。然后你可以这样做:
interface Properties {
[key: string]: string|number|boolean;
}
【讨论】:
properties: any;,那么它可以是任何东西,但我希望它是Object,具有任意数量的任何属性,或者具体来说它只是:数字|布尔值 |细绳。但是任何数量的这些属性。这在 TS 中可能吗?
也许你正在寻找这个
type Primitive = string | number | boolean
interface Data {
[key: string]: Primitive
}
const data1: Data = {
a: 1,
b: true,
c: 'asd'
}
// you basically dont need `Data` interface, instead you can use `Record` as below
const rec: Record<string, Primitive> = data1
【讨论】:
[key: string]:
你想要Record<> 类型:
interface Data {
properties: Record<string, number|boolean|string>
}
【讨论】: