简体   繁体   English

如何从 TS 文字联合类型推断 object 的键和值?

[英]How to infer keys and values of an object from TS literal union type?

i have two literal union types of strings and want them to be the possible keys and values of an object.我有两个文字联合类型的字符串,并希望它们成为 object 的可能键和值。

export type AlarmKeyword = 'R1' | 'R2';

export type ResourceTypes = 'nktw' | 'rtw' | 'nef' | 'rth' | 'hlf' | 'dlk';

The new type looks like this:新类型如下所示:

export type AlarmKeywordObject = {
  [P in AlarmKeyword]: { [T in ResourceTypes]: number };
};

But TS now complains about this code:但是 TS 现在抱怨这段代码:

      {
        R1: {
          rtw: 1,
        },
      }

Type '{ rtw: number;输入'{ rtw:数字; }' is missing the following properties from type '{ nktw: number; }' 缺少类型 '{ nktw: number; 中的以下属性; rtw: number; RTW:数字; nef: number; nef:数字; rth: number; rth:数字; hlf: number; hlf:数字; dlk: number; dlk:数字; }': nktw, nef, rth, hlf, dlk }': nktw, nef, rth, hlf, dlk

How can i ensure, that the keys are optional and not all of them are required?我如何确保密钥是可选的而不是所有密钥都是必需的?

Thank you!谢谢!

You can use question mark ?你可以使用问号? to mark that keys are optional:标记键是可选的:

type AlarmKeywordObject = {
    [P in AlarmKeyword]?: { [T in ResourceTypes]?: number }
};

Playground 操场

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

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