Kar*_*ner 0 typescript angular
我在这里有一个打字稿问题。
I have many model classes, that are all inherited from BaseModel
class BaseModel {
public isChecked: boolean;
}
class Animal extends BaseModel {
public id: number;
}
class Car extends BaseModel {
public hasHotWheels: boolean;
}
Run Code Online (Sandbox Code Playgroud)
Now I need to write a function that accepts arguments that are classes that inherit from the BaseModel. I can explicitly list all the classes, but I have more than 50 models that inherit from the BaseModel class, so my question is, can I somehow state that I expect the function parameter to inherit from a said class like so
function foo( _input: inherits from BaseModel ) {}
Run Code Online (Sandbox Code Playgroud)
泛型可以帮助:
function foo<TModel extends BaseModel>( _input: TModel ) {}
Run Code Online (Sandbox Code Playgroud)
描述泛型时可以使用许多类关键字,在 TS 路线图上有更多选项。类型推断可以轻松处理此类事情,并且当它失败时,您可以foo<FooModel>显式调用它,它仍然是类型安全的。
| 归档时间: |
|
| 查看次数: |
1076 次 |
| 最近记录: |