typescript - 如何定义将类型作为强类型参数的 Typescript 函数
问题描述
我想创建一个函数,该函数接受export class
扩展特定类型的类型(创建并正常导入)。我有一个Page
类和许多派生类。用简单的英语,我想要一个函数 accept Page
, DerivedPage
, AnotherDerivedPage
classes(而不是实例),显然,试图避免any
并保持强类型。
我该怎么做?
解决方案
如果您只想要 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) => { /* ... */ }
推荐阅读
- javascript - 在类的构造函数中从另一个属性引用一个属性的值
- oracle - MyBatis 支持多个数据库
- amazon-web-services - Cognito/Lambda:PreSignUp_SignUp 中的验证
- c# - 为什么datagrid不按行显示数据
- .net - 更新 .NET Core 托管捆绑包需要重新启动 IIS?
- c# - 从 KendoUI 编辑器自定义导出到 word 保存到 DB-屏幕截图没有导出到 word
- kotlin - 我的测试项目中的一些错误与gson的retrofit2
- autohotkey - 按钮自动激活
- angular - Formbuilder反应表单的自定义名称 - Angular 7
- ag-grid - 事件侦听器在网格之外工作,但在 ag-grid 中的单元格内不起作用