代码之家  ›  专栏  ›  技术社区  ›  Akxe

typescript:与前一个参数的解析类型相同的泛型类型

  •  4
  • Akxe  · 技术社区  · 8 年前

    我想知道,如果该泛型类型与前一个参数的解析类型相同,那么当该类型可以是多个类型时,如何指定该泛型类型。

    TypeScript playground

    function add<T extends (number | string)>(a: T, b: T): T {
        if (typeof a === 'string') {
            return a + b;
        } else if (typeof a === 'number') {
            return a + b;
        }
    }
    
    add('hello', ' world');
    add(1, 1);
    

    我想告诉编译器 T 是同一类型的,数字或字符串。我可能漏掉了一些语法。可能有条件类型(在某种程度上)….

    1 回复  |  直到 8 年前
        1
  •  1
  •   Titian Cernicova-Dragomir    8 年前

    不能在函数中缩小泛型参数的类型。所以当你测试 a 这不会告诉编译器 b 是。更重要的是,它不会告诉编译器函数的返回类型需要是什么

    function add<T extends (number | string)>(a: T, b: T): T {
        if (typeof a === 'string' && typeof b === 'string') {
            let result = a + b; // result is string, we can apply + 
            return result as T; // still an error without the assertion, string is not T 
        } else if (typeof a === 'number' && typeof b === 'number') {
            let result = a + b; // result is number, we can apply +
            return result as T; // still an error without the assertion, number is not T  
        }
        throw "Unsupported parameter type combination"; // default case should not be reached
    }
    

    在这种情况下,尽管可能有一个专用的实现签名在联合上工作(意味着不需要断言),并且公共签名是您以前使用的签名。

    function add<T extends number | string>(a: T, b: T): T
    function add(a: number | string, b: number | string): number | string {
        if (typeof a === 'string' && typeof b === 'string') {
            return a + b;
        } else if (typeof a === 'number' && typeof b === 'number') {
            return a + b;
        }
        throw "Unsupported parameter type combination"; // default case should not be reached
    }
    
    推荐文章