打字稿通用功能

时间:2019-02-04 15:04:05

标签: typescript function generics

我在打字稿中缺少有关泛型的知识。假设以下示例:

type Caster<T> = (original: unknown) => T

const castA = <T>(original) => original as T
//                 ^^^ Parameter 'original' implicitly has an 'any' type.
const castB: Caster = <T>(original) => original as T
//            ^^^ Generic type 'Caster' requires 1 type argument(s).            
const castC: Caster<T> = (original) => original as T
//                 ^^^ Cannot find name 'T'.      ^^^

castAcastBcastC做同样的事情:它们强制转换为T类型的值(很丑,但符合示例)。

类型Caster<T>描述了应用程序unknown -> T。我假设我可以创建此类函数的通用实现,但是castAcastBcastC都会产生编译错误(请参见注释)。

相反,以下方法效果很好:

// OK - but it's not generic
const castString: Caster<string> = (original: unknown) => original as string
// OK - but no reference to generic "Caster" type
const castGeneric = <T>(original: unknown) => original as T

在我看来有点晦涩。我如何获得这种行为? 它将非常有用(考虑工厂方法)

谢谢

2 个答案:

答案 0 :(得分:0)

const castC: Caster<T> = (original) => original as T

期望类型为string

const castC: Caster<string> = (original) => original as string

当您调用函数时,实际上是在使用泛型。因此,type Caster<T> = (original: unknown) => T使用泛型声明类型,而const castC: Caster<string> = (original) => original as string使用它


const castGeneric: Caster<T> = <T>(original: unknown) => original as T

Caster<T>castGeneric的类型声明,因此它需要实际的类型

答案 1 :(得分:0)

const castC:Caster<T> = ...

您需要给T指定某种类型 然后castC将转到(original: unknown) => T

例如const castD:Caster<string>constD:(original: unknown)=>string