How to make a generic add operator in TypeScript that works with numbers and strings

試著忘記壹切 提交于 2019-12-24 05:57:22

问题


While learning about generics in TypeScript, I wanted to try to recreate the following JavaScript:

function add(x, y){
    return x + y;
}

I tried like:

type StringOrNumber = string | number;

function add<MyType extends StringOrNumber>(x: MyType, y: MyType): MyType {
    return x + y;
}

This errors with:

error TS2365: Operator '+' cannot be applied to types 'MyType' and 'MyType'.

Why doesn't this work? I'd assume that MyType could be either a string or a number, and once "chosen" TypeScript would know it is either adding two strings or two numbers.


回答1:


A case that could also happen is that MyType can be string | number which extends StringOrNumber. For example add<string | number>('', 1); is a perfectly valid call to the function with the signature you have defined. A type extending a union type doesn't mean "pick exactly one".

Since your signature makes sense and you are learning about generics so we want to stick with it, we can also turn off type checking at that point. Sometimes typescript really can't figure out your complex scenario and you are left with no other option than to return (x as any) + y to abandon the type checking at this point.

Another way to handle this type of situation is with overloaded signatures like the following

function add(x: string, y: string): string;
function add(x: number, y: number): number;
function add(x: any, y: any): any {
    return x + y;
}

const t1: string = add(10, 1); // Type 'number' is not assignable to type 'string'.
const t2: number = add(10, 1); // OK
const t3: string = add('10', '1'); // OK
const t4: number = add('10', 1); // Argument of type '"10"' is not assignable to parameter of type 'number'.


来源:https://stackoverflow.com/questions/54470329/how-to-make-a-generic-add-operator-in-typescript-that-works-with-numbers-and-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!