gpt4 book ai didi

typescript ,将类型从对象映射到元组

转载 作者:行者123 更新时间:2023-12-03 16:35:06 24 4
gpt4 key购买 nike

考虑以下接口(interface):

interface Theme {
color: {
primary: {
light: string
base: string
dark: string
}
secondary: {
lighter: string
light: string
base: string
dark: string
darker: string
}
}
}


我正在尝试编写一个允许元组的类型,第一个元素映射到 colors 中的任何键,第二个映射到其下的任何键(即: base)。

IE:
['primary', 'light'] ✅ valid
['secondary', 'darker'] ✅ valid
['primary', 'darker'] 🛑 invalid

这是我在 tsplayground 上所做的尝试我在这里面临的问题是,如果我想允许多个键作为第一个参数传递,那么第二个需要满足所有第一个。有没有办法告诉 typescript 使用作为类型传递的文字值?
type PickThemeColor<C extends keyof Theme['color'] = keyof Theme['color']> = [
C,
keyof Theme['color'][C]
]

// 👇🏼 this complains because 'darker' doesnt appear in both 'primary' and 'secondary' keys

const x: PickThemeColor<'primary' | 'secondary'> = ['secondary', 'darker']

最佳答案

您在这里有 2 个选项,一个泛型,不幸的是您需要指定它或一个联合:

// A generic way
type Typle<K extends keyof Theme['color']> = [K, keyof Theme['color'][K]];

const test1: Typle<'primary'> = ['primary', 'light'];
const test2: Typle<'secondary'> = ['secondary', 'darker'];
const test3: Typle<'primary'> = ['primary', 'darker']; // fails

// A union way.
type Typle2 <K = keyof Theme['color']> = K extends keyof Theme['color'] ? [K, keyof Theme['color'][K]] : never;

const test4: Typle2 = ['primary', 'light'];
const test5: Typle2 = ['secondary', 'darker'];
const test6: Typle2 = ['primary', 'darker']; // fails

否则,您需要一个创建函数来避免所需的通用值。

// a helper function way.
const craeteType = <K extends keyof Theme['color']>(v: Typle<K>): Typle<K> => {
return v;
}

const test7 = craeteType(['primary', 'light']);
const test8 = craeteType(['secondary', 'darker']);
const test9 = craeteType(['primary', 'darker']); // fails

Playground

关于 typescript ,将类型从对象映射到元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62192543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com