简体   繁体   English

打字稿:如何为对象类型的键值对定义接口

[英]Typescript: How do I define an interface for an object type's key value pair

I have an object called externalObject that has various key:value pairs.我有一个名为externalObject的对象,它具有各种键:值对。

I also have a typescript interface that is defined as the following:我还有一个 typescript 接口,定义如下:

interface TestObject{
   externalObject?: {}
}

My question is how do I further set the type for the externalObject's key as string and the values that are passed inside externalObject as string or number?我的问题是如何进一步将 externalObject 的键的类型设置为字符串,并将在 externalObject 内部传递的值设置为字符串或数字?

Note: we do not always know the key:value pairs.注意:我们并不总是知道键值对。 They vary each time.他们每次都不同。

You can set any number of key/types on an interface in a similar way to assigning an object.您可以以类似于分配对象的方式在界面上设置任意数量的键/类型。 If you don't know the property names ahead of time, you can use a dynamic key:如果您事先不知道属性名称,则可以使用动态键:

export interface ITestObject {
  externalObject: {
    [key: string]: string | number;
  };
}

Alternatively, you can set the property as unknown and cast it to the proper type.或者,您可以将该属性设置为unknown并将其转换为正确的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Typescript:如何使用其值是数组中值的子集的键定义接口? - Typescript: How to define an interface with a key whose value is a subset of values in an array? 我是否必须使用接口来使用typescript定义对象的元素? - Do I have to use an interface to define the elements of an object with typescript? 如何通过在JavaScript对象中的多个键/值对中找到最小值来选择键/值对? - How do I select a key/value pair by finding the smallest value in a number of key/value pairs in a JavaScript object? 如何将对象数组转换为键/值对打字稿 - How to convert array of Object into key/value pair typescript TypeScript-如何将“键值”对添加到数组中的每个对象? - TypeScript- How to add a Key Value pair to each object in an Array? 如何从打字稿中的对象中分离键和值对 - How to separate key and value pair from an object in typescript 如何为以字符串为键和React SFC为值的对象包装定义TypeScript类型? - How to define TypeScript type for object wrapper that has string as a key & React SFC as a value? 如何在 TypeScript 中为我的常量定义接口或类型? - How can I define an interface or type in TypeScript for my constant? 如何为空数组定义TypeScript接口? - How do I define a TypeScript interface for an empty array? 如何将100个不同的选择名称及其选定的选项存储在对象中作为键值对 - how do you store 100s of different select names and their selected options in a object as a key value pair
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM