首页 > 解决方案 > 如何定义将类型作为强类型参数的 Typescript 函数

问题描述

我想创建一个函数,该函数接受export class扩展特定类型的类型(创建并正常导入)。我有一个Page类和许多派生类。用简单的英语,我想要一个函数 accept Page, DerivedPage, AnotherDerivedPage classes(而不是实例),显然,试图避免any并保持强类型。

我该怎么做?

标签: typescriptinheritancestrong-typingtypescript3.0

解决方案


如果您只想要 Page、DerivedPage、AnotherDerivedPage 类;你可以使用如下的东西:

function foo (foo: Page | DerivedPage | AnotherDerivedPage)

如果你想要一个扩展 Page 的参数,可能下面是要走的路:

function foo<T extends Page> (a: T) { ... }

编辑:
添加此类类型的示例以与箭头函数一起使用

type foo<T extends Page> = (v: T) => void
const fn: foo<DeribedPage> = (v) => { /* ... */ }

推荐阅读