问题描述
我有一个这样定义的有区别的联合:
enum ShapeKind {
Square = 'sqaure',Rectangle = 'rectangle',}
interface Square {
kind: ShapeKind.Square;
size: number;
}
interface Rectangle {
kind: ShapeKind.Rectangle;
width: number;
height: number;
}
type Shape = Square | Rectangle;
我希望能够从数据库中加载它们。我有一个带有以下签名的方法:
getShape(kind: ShapeKind,id: string): Shape
这将执行以下数据库查询,并根据记录的kind
字段返回与接口匹配的对象:
SELECT * FROM shapes WHERE id = ? AND kind = ? LIMIT 1
如果我传递了ShapeKind.Rectangle
,我知道它必须返回一个Rectangle
(或抛出一个未找到的错误),但是此刻无论我返回什么,返回类型始终为Shape
通过。
如何使编译器理解此规则?
解决方法
您可以使用function overload:
function getShape(kind: ShapeKind.Rectangle,id: string): Rectangle
function getShape(kind: ShapeKind.Square,id: string): Square
function getShape(kind: ShapeKind,id: string): Shape {
// Your query here
switch (kind) {
case ShapeKind.Rectangle:
return {
kind: ShapeKind.Rectangle,width: 1,height: 1,}
case ShapeKind.Square:
return {
kind: ShapeKind.Square,size: 1,}
}
}