TypeScript function return type based on input parameter

前端 未结 3 1138
梦毁少年i
梦毁少年i 2020-12-28 15:02

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

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 15:50

    Conditional Types to the rescue:

    interface Circle {
        type: "circle";
        radius: number;
    }
    
    interface Square {
        type: "square";
        length: number;
    }
    
    type TypeName = "circle" | "square"; 
    
    type ObjectType = 
        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(type: T) : ObjectType[]  {
        return shapes.filter(s => s.type == type) as ObjectType[];
    }
    
    const circles = getItems("circle");
    for (const circle of circles) {
        console.log(circle.radius);
    }
    

    Thanks Silvio for pointing me in the right direction.

提交回复
热议问题