typescript - 在 Typescript 中推断两个参数的基本类型

标签 typescript generics type-inference

在 Typescript 中实现集合上的泛型函数时,我注意到编译器无法推断两个参数的基本类型。

function union<T>(first: Set<T>, second: Set<T>): Set<T> {
  const newSet = new Set<T>(first);
  for (const element of second)
    newSet.add(element);
  return newSet;
}

class Animal { }
class Dog extends Animal {
  bark() { console.info('Woof!'); }
}
class Cat extends Animal {
  meow() { console.info('Meow!'); }
}

const a = new Set<Dog>();
const b = new Set<Cat>();

然后,如果我调用 union,Typescript 无法推断 T 应该是 Animal

const c = union(a, b);
// This results in the error:
// Argument of type 'Set<Cat>' is not assignable to parameter of type 'Set<Dog>'.
// Property 'bark' is missing in type 'Cat' but required in type 'Dog'.ts(2345)

但是如果我明确地使用 T = Animal 调用 union,它就可以正常工作:

const d = union<Animal>(a, b);

我做错了什么?

最佳答案

尝试使用类型联合:

function union<T extends Animal, U extends Animal>(first: Set<T>, second: Set<U>) {
    const newSet = new Set<T | U>(first);
    for (const element of second)
        newSet.add(element);
    return newSet;
}

class Animal { }

class Dog extends Animal {
    bark() { console.info('Woof!'); }
}
class Cat extends Animal {
    meow() { console.info('Meow!'); }
}

const a = new Set<Dog>();
const b = new Set<Cat>();

const c = union(a, b);

Playground

添加额外的泛型参数U有助于TS推断两个Set的类型

关于typescript - 在 Typescript 中推断两个参数的基本类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68376615/

相关文章:

f# - 无限类型(又名递归类型)在 F# 中是不可能的吗?

TypeScript:当类型推断正确检测到类型时显式设置类型是不好的做法吗?

scala - 在 Scala 中设计一个方便的默认值映射

typescript - 实例化类的通用 TypeScript 函数

java - 具有继承支持泛型问题的构建器模式

javascript - 如何从 nestjs guard 访问数据库

node.js - 如何生成使用 NESTJS 完成的 API 的生产版本

c# - 为什么要限制在泛型类型中的接口(interface)?

javascript - 根据索引的嵌套数组的总和

angular - 无法读取未定义的属性 'native-element'