简体   繁体   English

在 Typescript 中,如果事先不知道对象的属性,您如何键入它?

[英]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.

相关问题 当属性是可选的时,如何在 Typescript 中解构对象? - How to descturcture an object in Typescript when properties are optional? 你如何让 TypeScript 知道 state 变量和设置器 function 是不同的类型而不是联合类型(TS7053) - How do you let TypeScript know that the state variable and setter function are different types and not a union type (TS7053) 如何将自定义属性传递给TypeScript + StyledCompoments? - How do you pass custom properties to TypeScript + StyledCompoments? 如果你想要所有 css 属性作为 typescript 中的一个类型,你放什么? - if you want all css properties as a type in typescript what do you put? 如何键入枚举和对象以具有相同的属性 React Typescript - How to type enum and object to have same properties React Typescript 打字稿:如何为对象类型的键值对定义接口 - Typescript: How do I define an interface for an object type's key value pair 如何在 TypeScript 的 catch 块中键入错误属性? - How do you type an error property in a catch block in TypeScript? 你如何在 React Native 中为 useRef 钩子设置 Typescript 类型? - How do you set the Typescript type for useRef hook in React Native? 嵌套对象属性的 Typescript 泛型类型 - Typescript generic type for nested object properties 你如何将 React 回调 function 传递给 typescript object? - How do you pass a React callback function to a typescript object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM