我有这样的代码(TS游乐场):
const createComp = <T extends {
modifiers: {
[key: string]: string;
};
defaultMods: keyof T["modifiers"];
}
>(com: T) => com;
const style = createComp({
modifiers: {
blue: 'blue',
red: 'red'
},
defaultMods: 'red' // correct. defaultMods type is 'blue' | 'red'
});正如我所期望的那样,它将defaultMods类型推断为'blue' | 'red'。
但是,当我试图将extends类型提取为Component类型时,如下面(TS游乐场)所示:
type Component = {
modifiers: {
[key: string]: string;
};
defaultMods: keyof Component["modifiers"];
}
const createComp = <T extends Component>(com: T) => com;
const style = createComp({
modifiers: {
blue: 'blue',
red: 'red'
},
defaultMods: '' // defaultMods type is string
});它不将defaultMods类型返回为'blue' | 'red'。我错过了什么吗?
发布于 2022-02-06 17:40:59
keyof Component["modifiers"]总是决定采用string。您将需要一个额外的Component类型参数来表示修饰符,并在您的函数中推断:
type Component<TModifiers extends Record<string, string>> = {
modifiers: TModifiers;
defaultMods: keyof TModifiers;
}
const createComp = <TModifiers extends Record<string, string>>(com: Component<TModifiers>) => com;
const style = createComp({
modifiers: {
blue: 'blue',
red: 'red'
},
defaultMods: '' // it should be 'blue' | 'red'
});https://stackoverflow.com/questions/71009816
复制相似问题