简体   繁体   English

如何在 TypeScript 中使用可选键创建索引 object?

[英]How can I create an indexed object with optional keys in TypeScript?

I have the following type - export type Sizes = 'small' | 'medium' | 'big'我有以下类型 - export type Sizes = 'small' | 'medium' | 'big' export type Sizes = 'small' | 'medium' | 'big' export type Sizes = 'small' | 'medium' | 'big' and I want to use this type as keys for an object I'm creating: export type Sizes = 'small' | 'medium' | 'big' ,我想将此类型用作我正在创建的 object 的键:

type SizeInformation = {
  [key in Sizes]: string;
}

However, the desired functionality here is that this type (and therefore the object that will be created based on it) doesn't necessarily need to have all keys named, or none at all, but if a key goes into the object, it should be of type Sizes .然而,这里所需的功能是这种类型(以及因此将基于它创建的 object)不一定需要命名所有键,或者根本不需要,但如果键进入 object,它应该类型为Sizes

As such, an empty object would be valid, an object with just the key medium would also be valid, but if an object has the keys medium and sea , it is not valid, as, again, all keys need to be of type Sizes .因此,一个空的 object 是有效的,一个只有密钥medium的 object 也是有效的,但是如果一个 object 有密钥mediumsea ,它是无效的,因为,同样,所有密钥都必须是Sizes类型.

I've played around with Partial but to no avail.我玩过Partial但无济于事。

How can I achieve that?我怎样才能做到这一点? Thank you.谢谢你。

You should leave your index signature the same.你应该让你的索引签名保持不变。 Index signatures are stating for what the shape of properties/values would be if they were enumerable (or actually assigned).索引签名说明了属性/值的形状,如果它们是可枚举的(或实际分配的)。 Therefore, you should always have your index signatures as non-undefined.因此,您应该始终将索引签名设为非未定义。 If you want strict index signature access where you need to handle for a key not being in the object, then you should enable the noUncheckedIndexedAccess config property because it will force you to handle for the undefined case when using index signatures.如果你想要严格的索引签名访问,你需要处理不在 object 中的键,那么你应该启用noUncheckedIndexedAccess配置属性,因为它会强制你在使用索引签名时处理undefined的情况。 See the reference on noUncheckedIndexedAccess 请参阅noUncheckedIndexedAccess上的参考资料

It is very simple.这很简单。 You can use two Utility Types , Partial and Record , together.您可以同时使用两种Utility TypesPartialRecord

type Sizes = 'small' | 'medium' | 'big'

// Following code will create type that can accept keys which are of type Sizes and which will be optional
type SizeInformation = Partial<Record<Sizes, string>>;


const obj : SizeInformation = {
    big: 'big',
    medium: 'medium',
    small:'small'
}

For referencehttps://www.typescriptlang.org/docs/handbook/utility-types.html供参考https://www.typescriptlang.org/docs/handbook/utility-types.html

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM