使用Typescript泛型的显式值类型约束?

布兰登

我有这个功能:

function filterByCourseNumber(data: IPost[] | IExam[], courses: string[]) {
  if (courses.length === 0) return data;
  return data.filter((item) => _includes(courses, item.courseNumber));
}

当我通过时它工作正常IPost[],但是当我这样做时:

exams = filterByCourseNumber(exams, filters.courses)

我有这个错误:

Type 'IPost[]' is not assignable to type 'IExam[]'.
  Type 'IPost' is not assignable to type 'IExam'.
    Types of property 'claimer' are incompatible.
      Type 'string | undefined' is not assignable to type 'string'.
        Type 'undefined' is not assignable to type 'string'.ts(2322)
let exams: IExam[]

我知道我需要使用泛型,但是我不知道如何编写接口。

我试过了:

function filterByCourseNumber<T>(data: T[], courses: string[]): T[] {
  if (courses.length === 0) return data;
  return data.filter((item) => _includes(courses, item.courseNumber));
}

但是item.courseNumber有错误:

Property 'courseNumber' does not exist on type 'T'.

我想我已经接近了,但是我不确定如何让我的函数知道T只能是IPostor IExam

卡罗尔·马耶夫斯基(Karol Majewski)

将您的类型参数限制为IPost | IExam类型

function filterByCourseNumber<T extends IPost | IExam>(data: T[], courses: string[]): T[] {

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用受约束的泛型值类型在 TypeScript 中创建对象?

泛型无法显式转换类型

泛型类型约束不启用没有显式强制转换的赋值

如何在TypeScript中显式定义泛型返回类的返回类型?

指定其他类型时,如何让TypeScript推断受约束的泛型类型的值?

TypeScript 类型获取约束函数类型泛型的返回类型

使用泛型时,休眠的未绑定类型和没有显式的目标实体

Java泛型-构造函数调用的显式类型参数

泛型类型用于显式转换的用法

Typescript泛型类型约束和类型兼容性

typescript:具有基本类型约束的泛型类型

泛型类型错误:无法显式专门化泛型类型

泛型类型的泛型构造函数的显式类型注释

Typescript:从泛型类型获取文字值

TypeScript-泛型约束可以提供“允许的”类型吗?

如何在 Typescript 函数接口中约束泛型类型?

Typescript中具有泛型的子类型约束

Typescript:泛型,使用泛型扩展类型

使用泛型类型混淆TypeScript错误

使用new()定义TypeScript泛型类型

TypeScript泛型类型的泛型类型

为什么不能使用显式泛型参数调用泛型扩展方法?

不能在IEnumerable中使用泛型类型的约束?

如何使用基于泛型的条件类型来描述约束?

具有类型约束的 Go 泛型:不能在赋值中使用 false(无类型布尔常量)作为 T 值

TypeScript:使用受约束的泛型不匹配索引查找

没有显式声明类型的打字稿自动泛型类型

对包含的泛型类型参数的类型约束

泛型类型推断的 Typescript 泛型