```tsx function minimumLength( obj: Type, minimum: number ): Type { if (obj.length >= minimum) { return obj; } else { return { length: minimum }; //Type '{ length: number; }' is not assignable to type 'Type'. //'{ length: number; }' is assignable to the constraint of type 'Type', but 'Type' could be instantiated with a different subtype of constraint '{ length: number; }'. } }
```tsx function add (a : T, b : T ){ return a + b }
// Operator '+' cannot be applied to types 'T' and 'T'.
// a,b不一定可以相加 ```
修改办法:
```ts
function isSet(x : any) : x is Set { return x instanceof Set }
function add(a : number, b : number) : number; function add(a : string, b : string) : string; function add(a : Set, b : Set) : Set; function add(a : T, b : T) : T{ if(isSet(a) && isSet(b)){ return new Set([...a, ...b]) as any } return (a as any) + (b as any) }
const a = new Set(["apple", "redhat"]) const b = new Set(["google", "ms"]) console.log(add(a, b)) console.log(add(1, 2)) console.log(add("a", "k") ```
划重点:利用重载约束跨类型方法的使用
思考:如果……
```tsx function add(a : any, b : any) : any { // } ```