在使用索引签名和联合类型时,我试图在TypeScript中获得缩小的类型,而又不直接区分它们,例如使用switch case语句。
下面的代码在调用带有形状的doubleFn变量时会引发错误,尽管在运行时正确地将形状作为圆返回,但将doubleFn推断为用于将半径加倍并调用它的函数。
是否可以缩小doubleFn的类型,以使其理解为与给定形状的匹配对?
Link to TypeScript playground with the same code
enum Shapes {
Circle,Square,}
interface ShapeProperties {
[Shapes.Circle]: {
radius: number;
};
[Shapes.Square]: {
length: number;
};
}
type FunctionsType = {
[key in Shapes]: (a: ShapeProperties[key]) => ShapeProperties[key];
};
const doubleFunctions: FunctionsType = {
[Shapes.Circle]: (circleProps: ShapeProperties[Shapes.Circle]) => ({
radius: circleProps.radius * 2,}),[Shapes.Square]: (squareProps: ShapeProperties[Shapes.Square]) => ({
length: squareProps.length * 2,};
interface Circle {
type: Shapes.Circle;
props: ShapeProperties[Shapes.Circle];
}
interface Square {
type: Shapes.Square;
props: ShapeProperties[Shapes.Square];
}
type Shape = Circle | Square;
function getShape(): Shape {
return { type: Shapes.Circle,props: { radius: 5 } };
}
const shape = getShape();
const doubleFn = doubleFunctions[shape.type];
doubleFn(shape.props);