TypeScript 函数根据输入参数返回类型 [英] TypeScript function return type based on input parameter
本文介绍了TypeScript 函数根据输入参数返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几个不同的接口和对象,每个接口和对象都有一个 type
属性.假设这些是存储在 NoSQL 数据库中的对象.如何根据输入参数 type
创建具有确定性返回类型的通用 getItem
函数?
interface Circle {类型:圆圈";半径:数量;}界面广场{类型:正方形";长度:数量;}const 形状:(圆形 | 方形)[] = [{ 类型:圆",半径:1 },{ 类型:圆",半径:2 },{ 类型:正方形",长度:10 }];函数getItems(类型:圆形"|方形"){返回shapes.filter(s => s.type == type);//将此视为来自数据库的项目//我希望这个函数的返回类型是//基于作为参数提供的 `type` 值的确定性.}const circles = getItems("circle");for (const circle of circle) {控制台日志(圆.半径);^^^^^^}
<块引用>
圆"类型上不存在半径"属性 |方'.
解决方案
条件类型
:
interface Circle {类型:圆圈";半径:数量;}界面广场{类型:方形";长度:数量;}type TypeName = "circle";|正方形";类型 ObjectType=T延伸圆"?圆圈 :T延伸正方形"?正方形 :绝不;const 形状:(圆形 | 方形)[] = [{ 类型:圆",半径:1 },{ 类型:圆",半径:2 },{ 类型:正方形",长度:10 }];function getItems(type: T) : ObjectType[] {返回 shape.filter(s => s.type == type) 作为 ObjectType[];}const circles = getItems("circle");for (const circle of circle) {控制台日志(圆.半径);}
感谢 Silvio 为我指明了正确的方向.
I have a few different interfaces and objects that each have a type
property. Let's say these are objects stored in a NoSQL db. How can I create a generic getItem
function with a deterministic return type based on its input parameter 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);
^^^^^^
}
Property 'radius' does not exist on type 'Circle | Square'.
解决方案
Conditional Types
to the rescue:
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);
}
Thanks Silvio for pointing me in the right direction.
这篇关于TypeScript 函数根据输入参数返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文