TS接口-具有任何属性的对象

时间:2020-09-23 10:32:43

标签: typescript interface properties

如何在TypeScript中为具有任何属性的对象定义接口?

interface Data {
  properties: Properties;
}

interface Properties {
  ...
}

3 个答案:

答案 0 :(得分:1)

具有任何属性的对象就像any。为什么要定义其他接口? 原因之一可能是您想允许特定的值类型。然后您可以执行以下操作:

interface Properties {
  [key: string]: string|number|boolean;
}

答案 1 :(得分:1)

您要使用Record<>类型:

interface Data {
  properties: Record<string, number|boolean|string>
}

答案 2 :(得分:1)

也许您正在寻找这个

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