从打字稿中的数组变量对象创建记录

Create a Record from an object of arrays variable in typescript

我有一个数组对象变量:

cssColorsObject = {
    red: ["lightsalmon", "salmon", "darksalmon", "lightcoral", "indianred", "crimson", "firebrick", "red", "darkred"],
    orange: ["coral", "tomato", "orangered", "gold", "orange", "darkorange"],
    yellow: [...
}

我想为包含一些键(例如“红色”、“橙色”、“黄色”)以及该键颜色的部分或全部属性的未来对象变量创建一个 type/interface ,例如:

{
    red: ["lightsalmon", "salmon"], // OK
    orange: [], //OK
    yellow: ["lightsalmon"], // NOT OK - because light salmon is a color associated with the "red" key in the original object
}

我已经计算出以下内容:

type CssColorKeys = keyof typeof cssColorsObject; // = "red" | "orange" | "yellow" | "green" , etc
type CssColorValues = typeof cssColorsObject[CssColorKeys][number]; // = "lightsalmon" | "salmon"... | "maroon"
type NewRecord = Record<CssColorKeys, CssColorValues> // Not what I want as this requires all properties and the exact same array.

我想我需要使用部分,但我很难在这里实现它们。


@captain-yossarian 的回答完全归功于@captain-yossarian。我只是想根据他的回答添加一个简化的解决方案:

type CssColorsPartial = Partial<{
    [Prop in keyof typeof cssColorsObject]: Array<typeof cssColorsObject[Prop][number]>;
}>;

我为具有强制键和可选数组值的映射类型创建了另一个 type here

首先,你需要使 cssColorsObject 不可变。

const cssColorsObject = {
    red: ["lightsalmon", "salmon", "darksalmon", "lightcoral", "indianred", "crimson", "firebrick", "red", "darkred"],
    orange: ["coral", "tomato", "orangered", "gold", "orange", "darkorange"],
    yellow: ['lemon']
} as const

然后遍历 cssColorsObject 个键并创建所需的类型。

type PartialCSS<T extends Record<string, ReadonlyArray<string>>> =
    Partial<{
        [Prop in keyof T]: Array<T[Prop][number]>
    }>

我曾经将 T[Prop] 数组解压缩到新的类似 Array<T[Prop][number]> 中,因为 T[Prop] 是不可变的元组,其中保留了元素的顺序,而新类型不需要精确的元素顺序。缺点,它允许你使用两个相似的元素。

完整代码:

const cssColorsObject = {
    red: ["lightsalmon", "salmon", "darksalmon", "lightcoral", "indianred", "crimson", "firebrick", "red", "darkred"],
    orange: ["coral", "tomato", "orangered", "gold", "orange", "darkorange"],
    yellow: ['lemon']
} as const


type PartialCSS<T extends Record<string, ReadonlyArray<string>>> =
    Partial<{
        [Prop in keyof T]: Array<T[Prop][number]>
    }>

const result: PartialCSS<typeof cssColorsObject> = {
    red: ['salmon'],
    yellow:['salmon'] // expected error
}

Playground