我怎樣才能為這個轉換案例實作型別安全?我正在映射palette并將任何帶有條目的物件轉換為鍵值對,就像 tailwindcss 對其顏色配置所做的那樣。但是,型別colors不包含灰色,而僅包含未轉換的條目鍵作為型別。
const palette = {
white: 'white',
gray: {
100: '#eeeeee',
200: '#e0e0e0',
300: '#bbbbbb',
},
};
type ColorVariants = keyof typeof palette;
function convertToColors(color: ColorVariants) {
return Object.fromEntries(
Object.entries(palette[color]).map(([key, value]) => [`${color}${key}`, value]),
);
}
/**
result ->
{
"gray100": "#eeeeee",
"gray200": "#e0e0e0",
"gray300": "#bbbbbb",
}
*/
const grays = convertToColors("gray")
此處型別不正確
// Resulting Type
// const colors: {
// white: string;
// }
//
// Expecting Type
// const colors: {
// white: string;
// gray100: string;
// gray200: string;
// gray300: string;
// }
const colors = {
white: palette.white,
...convertToColors("gray")
}
uj5u.com熱心網友回復:
您現在可以使用模板文字型別。
讓我們convertToColors對此進行編輯:
function convertToColors<Color extends ColorVariants>(color: Color): Variants<Color, typeof palette[Color]> {
return Object.fromEntries(
Object.entries(palette[color]).map(([key, value]) => [`${color}${key}`, value]),
) as never; // cast to return type; "ignore" error
}
它需要一種顏色,并為我們提供該顏色的變體物件。
這是建議的Variants型別:
type Variants<K extends string, T extends string | Record<string | number, string>> = T extends string ? T : {
[V in keyof T as V extends string | number ? `${K}${V}` : never]: T[V];
};
首先它檢查給定的顏色是否沒有任何變體(它只是一個字串,而不是一個物件)。然后它將變體中的所有鍵重新映射為變體 其強度。
你可以看到它在這里作業得很好。
uj5u.com熱心網友回復:
你可以在這種情況下使用聯合:
type ColorVariants = string | {[prop:number]:string};
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481037.html
上一篇:將型別分配給動態訪問的物件值
下一篇:打字稿有條件地使屬性成為可選
