可以使用类型别名和联合类型来实现此功能。假设我们有以下部分类型:
type Square = {
kind: "square",
size: number
}
type Circle = {
kind: "circle",
radius: number
}
我们可以定义一个类型别名来表示上述所有部分类型的联合类型:
type Shape = Square | Circle;
然后,我们可以编写一个函数,它接受一个类型鉴别器和部分类型,并返回完整类型。例如,我们可以定义一个函数来接受“kind”鉴别器和部分类型,并返回完整类型:
function createShape(kind: T['kind'], data: Omit): T {
if (kind === 'square') {
return { kind, ...data, size: 10 } as T;
}
else if (kind === 'circle') {
return { kind, ...data, radius: 5 } as T;
}
}
const mySquare = createShape('square', { size: 20 }); // { kind: "square", size: 20 }
const myCircle = createShape('circle', { radius: 3 }); // { kind: "circle", radius: 3 }
在上面的示例中,我们使用类型鉴别器“kind”和部分类型创建出完整类型,并返回生成的类型。