V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
4196

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

  •  
  •   4196 · Sep 18, 2021 · 1581 views
    This topic created in 1685 days ago, the information mentioned may be changed or developed.
    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 replies    2021-09-18 17:24:10 +08:00
    Zhuzhuchenyan
        1
    Zhuzhuchenyan  
       Sep 18, 2021
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2647 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 03:14 · PVG 11:14 · LAX 20:14 · JFK 23:14
    ♥ Do have faith in what you're doing.