简体   繁体   English

在打字稿中定义的地图列表中的动态键名称

[英]Dynamic Key name with in the defined list for a Map in typescript

I am trying to define the type in typescript.. that should accept at least one key-value (within the defined list).我正在尝试在 typescript 中定义type ,它应该至少接受一个键值(在定义的列表中)。 If the data has at least one defined key among the list, remaining should be optional.如果数据在列表中至少有一个定义的键,则剩余应该是可选的。

Is there any way we can do that in typescript.有什么办法可以在打字稿中做到这一点。

type values = 'a' | 'b' | 'c' | 'd';
type data<T extends string, K> = Record<T, K>;

// current output:
const d:data<values, string> = {
  'a': 'sample text',
  'b': 'b sample text',
  'c': 'c sample text'
};

// Expecting output
const d:data<values, string> = {
  'a': 'sample text'
}

In the above example, d expects every key in the values .在上面的例子中, d期望values每个键。 I did try partial it is making all values are optional.我确实尝试了partial它使所有值都是可选的。

my intention is when the incoming data should have at least one key from the values .我的意图是传入的数据应该至少有一个来自values key

Note: Values are so dynamic or have a longer list.注意:值是如此动态或具有更长的列表。

You can do this by intersecting a mapped type to require each property individually with Partial<T>您可以通过将映射类型与Partial<T>相交以单独要求每个属性来做到这一点

type AtLeastOne<T> = {
    [K in keyof T]: {
        [K2 in K]: T[K]
    }
}[keyof T] & Partial<T>

How it works:这个怎么运作:

  1. Loop over all the keys in the provided record, and set the type in the resulting record to be an object with just that key { [K in keyof T] ... }遍历提供的记录中的所有键,并将结果记录中的类型设置为只有该键的对象{ [K in keyof T] ... }
  2. Get the union of all elements in the mapped type [keyof T]获取映射类型中所有元素的并集[keyof T]
  3. Intersect the union with Partial<T> to require any other provided properties to be the correct type将联合与Partial<T>相交以要求任何其他提供的属性是正确的类型

Demo: Playground演示: 游乐场

type AtLeastOne<T> = {
    [K in keyof T]: {
        [K2 in K]: T[K]
    }
}[keyof T] & Partial<T>

type Data<K extends string, T> = AtLeastOne<Record<K, T>>

type Keys = 'a' | 'b' | 'c' | 'd'

type Result = Data<Keys, string>

const x: Data<Keys, string> = {
    a: '' // ok
}

const y: Data<Keys, string> = {} // error

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

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