gpt4 book ai didi

TypeScript 函数返回类型基于输入参数

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:07 26 4
gpt4 key购买 nike

我有几个不同的接口(interface)和对象,每个接口(interface)和对象都有一个 type 属性。假设这些是存储在 NoSQL 数据库中的对象。如何根据输入参数 type 创建具有确定性返回类型的通用 getItem 函数?

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);
^^^^^^
}

Property 'radius' does not exist on type 'Circle | Square'.

最佳答案

Conditional Types救援:

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 为我指明了正确的方向。

关于TypeScript 函数返回类型基于输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com