我想创建一个类型安全的方法,根据主要类型(当前是枚举)的值,将辅助键分配给对象。我尝试了以下操作,但类型
Test
被键入为 string
而不是允许值的并集。我怎样才能做到这一点?
export enum PrimaryImageType {
Artnum = "ARTNUM",
RMA = "RMA",
}
export const SecondaryImageTypes: Record<PrimaryImageType, string[]> = {
[PrimaryImageType.Artnum]: [
"LDA_OVP",
"LDA_PALETTE",
"LDA_LABEL",
"LDA_VERPACKHINWEIS",
"LDA_MASTERKARTON",
],
RMA: [
],
};
export type SecondaryType<P extends PrimaryImageType> = typeof SecondaryImageTypes[P][number];
type Test = SecondaryType<PrimaryImageType.Artnum>;
// Test is typed as string, I expect it to be "LDA_OVP" | "LDA_PALETTE" | "LDA_LABEL" | "LDA_VERPACKHINWEIS" | "LDA_MASTERKARTON"
// I want to use those types similar to this:
export interface Image<P extends PrimaryImageType> {
id: number,
imageType: P,
typeID: string,
secondaryType: SecondaryType<P>,
}
// TS should enforce the union of secondary types:
const testImg: Image<PrimaryImageType.Artnum> = {
id: 1,
imageType: PrimaryImageType.Artnum,
typeID: "asd",
secondaryType: "INVALID", // should be invalid
}