typescript - 基于输入参数的 TypeScript 函数返回类型
问题描述
我有几个不同的接口和对象,每个接口和对象都有一个type
属性。假设这些是存储在 NoSQL 数据库中的对象。如何getItem
根据输入参数创建具有确定性返回类型的泛型函数type
?
interface Circle {
type: "circle";
radius: number;
}
interface Square {
type: "square";
length: number;
}
const shapes: (Circle | Square)[] = [
{ type: "circle", radius: 1 },
{ type: "circle", radius: 2 },
{ type: "square", length: 10 }];
function getItems(type: "circle" | "square") {
return shapes.filter(s => s.type == type);
// Think of this as items coming from a database
// I'd like the return type of this function to be
// deterministic based on the `type` value provided as a parameter.
}
const circles = getItems("circle");
for (const circle of circles) {
console.log(circle.radius);
^^^^^^
}
类型“圆”上不存在属性“半径”| 正方形'。
解决方案
interface Circle {
type: "circle";
radius: number;
}
interface Square {
type: "square";
length: number;
}
type TypeName = "circle" | "square";
type ObjectType<T> =
T extends "circle" ? Circle :
T extends "square" ? Square :
never;
const shapes: (Circle | Square)[] = [
{ type: "circle", radius: 1 },
{ type: "circle", radius: 2 },
{ type: "square", length: 10 }];
function getItems<T extends TypeName>(type: T) : ObjectType<T>[] {
return shapes.filter(s => s.type == type) as ObjectType<T>[];
}
const circles = getItems("circle");
for (const circle of circles) {
console.log(circle.radius);
}
感谢 Silvio 为我指明了正确的方向。
推荐阅读
- r - r geom_map 似乎需要地图中的区域列
- swift - 如何将重新排序的 Tableview 单元格保存到核心数据
- html - 尝试在 Parallels Desktop 中实现网站图标
- c# - dll文件可以用作即插即用模块吗
- javascript - Next.js 与 Express 后端
- spring - 无法运行以下使用 JDBC 模板的 Spring Boot 应用程序
- apache-spark - Kubernetes 上的 SparkPi - 找不到或加载主类?
- config - Snakemake:在 YAML 配置文件中指定工作目录
- timer - 如何在flutter中进行倒计时?
- apache-kafka - 卡夫卡消费者没有消费任何消息