V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
4196
V2EX  ›  TypeScript

TS 怎么或者可以不可以实现类似的函数(签名),根据调用时传入的泛型类型,决定返回值的类型

  •  
  •   4196 · 2021-09-18 15:24:11 +08:00 · 1003 次点击
    这是一个创建于 922 天前的主题,其中的信息可能已经有所发展或是发生改变。
    interface A {
        A: string;
    };
    interface B {
        B: string;
    }
    function returnTwoType<T extends A | B>(type: 'A' | 'B'): T {
        if (type === 'A') {
            const res = { A: '类型 A' };
            // Type '{ A: string; }' is not assignable to type 'T'.
            // '{ A: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A | B'.
            return res
        }
        else {
            const res = {
                B: '类型 B'
            };
            // Type '{ B: string; }' is not assignable to type 'T'.
            // '{ B: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A | B'.
            return res
        }
    }
    
    const a = returnTwoType<A>('A')
    const b = returnTwoType<B>('B')
    
    1 条回复    2021-09-18 17:24:10 +08:00
    Zhuzhuchenyan
        1
    Zhuzhuchenyan  
       2021-09-18 17:24:10 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1420 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 17:28 · PVG 01:28 · LAX 10:28 · JFK 13:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.