如何根據 Typescript 中另一個屬性的值動態定義屬性的型別?
示例:我有這種型別的主題,并且希望這些appearance型別是基于variantType屬性的可能性的聯合:
type Theme = {
button: {
variantType: {
normal: { appearance1: { color: 'red' } };
success: { appearance1: { color: 'red' }, appearance2: { color: 'blue' } };
newVariant: { anyNewAppearance: { color: 'orange' } };
};
};
};
type VariantType<Component extends keyof Theme> =
'variantType' extends keyof Theme[Component]
? keyof Theme[Component]['variantType']
: unknown;
type VariantAppearance<Variant extends keyof Theme['button']['variantType']> =
keyof Theme['button']['variantType'][Variant];
type ButtonProps = {
variantType: VariantType<'button'>;
appearance: VariantAppearance<ButtonProps['variantType']>; // Here is the problem
};
預期結果示例(不允許,我的意思是打字稿錯誤):
// Allowed, variantType="normal" allows appearance "appearance1"
<Button variantType="normal" appearance="appearance1" />
// NOT allowed, variantType="normal" allows only appearance "appearance1"
<Button variantType="normal" appearance="appearance2" />
// NOT allowed, variantType="newVariant" allows only appearance "anyNewAppearance"
<Button variantType="newVariant" appearance="appearance2" />
// Allowed, variantType="newVariant" allows appearance "anyNewAppearance"
<Button variantType="newVariant" appearance="anyNewAppearance" />
目前它的型別是 never

uj5u.com熱心網友回復:
要派生型別,您可以將 Variant 作為 ButtonProps 的泛型傳入。然后,在定義 Button 組件時,從引數中推斷出泛型。
type ButtonProps<T extends VariantType<'button'>> = {
variantType: T;
appearance: VariantAppearance<T>;
};
function Button<T extends VariantType<'button'>>(props: ButtonProps<T>) {
return <></>;
}
這應該得到你正在尋找的結果。

在不使 ButtonProps 通用的情況下這樣做的第二種方法是使 ButtonProps 成為如下可能性的聯合:
type GenerateButtonProps<V extends VariantType<'button'>> = V extends any ? {
variantType: V;
appearance: VariantAppearance<V>
} : never;
type ButtonProps = GenerateButtonProps<VariantType<'button'>>;
function Button(props: ButtonProps) {
return <></>;
}
雖然,此方法會產生更詳細的錯誤訊息。

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/513152.html
標籤:反应打字稿类型
