有两个问题需要解决:
Problem 1: Mapped type with extra properties个
您需要使用intersection type:
type IconType = 'file' | 'emoji' | 'external'
type IconFile<U extends IconType & string> = { type: U } & { [P in U]: string }
const x: IconFile<'file'> = {
type: 'file',
file: 'string'
}
请注意类型为字符串的IconFile上的额外泛型参数.
Problem 2: Map union type to another union type个
我们想要一件IconFile<'file'> | IconFile<'emoji'> | IconFile<'external'>
码的
您可以对distributing over the members of the union type使用条件类型
type DistributeToIconFile<U extends IconType & string> = U extends string
? IconFile<U>
: never;
type IconFileAsUnion = DistributeToIconFile<IconType>
// ^?
// type IconFileAsUnion = IconFile<'file'> | IconFile<'emoji'> | IconFile<'external'>
const a: IconFileAsUnion = {
type: 'file',
file: 'myfile'
};
见TypeScript: Map union type to another union type
请注意,Simple IconFile<IconType>
不会分发unions 成员
const nodDistributedBadApproach: IconFile<IconType> = {
type: 'file',
file: 'string1',
emoji: 'string2',
external: 'string3'
}
Playground个