[英]In Typescript, how do you type an object when it's properties are not know beforehand?
I'm relatively new to typescript so pardon me if I'm missing something obvious.我对打字稿比较陌生,所以如果我遗漏了一些明显的东西,请原谅我。 I'm using typescript with ReactJS and I am trying to define types for an API response.
我在 ReactJS 中使用打字稿,我正在尝试为 API 响应定义类型。
The API docs say there's a meta
property which is an object but it's key/values can can't be predicted. API 文档说有一个
meta
属性,它是一个对象,但它的键/值无法预测。 ie IE
{
...
meta: {
property1: value1 //(can be string/number/array)
property2: value2
.
.
.
propertyN: valueN
}
}
How do I type this effectively?我如何有效地输入? My eslint complaints when I try
{ meta: object }
so I'm assuming that's no good.当我尝试
{ meta: object }
时,我的 eslint 抱怨所以我认为这不好。
Since you have no idea what it's going to contain, other than that it's going to be an object, you can use:由于您不知道它将包含什么,除了它将成为一个对象之外,您可以使用:
{ [key: string]: unknown };
It's not exactly effective - you'll have to do further explicit type-narrowing on every property value, but at least it's type safe (unlike any
).它并不完全有效- 您必须对每个属性值进行进一步的显式类型缩小,但至少它是类型安全的(与
any
不同)。
如果您知道它can be string/number/array
,只需像这样定义它:
type MetaType = { [key: string]: string | number | any[] };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.