[英]Typescript: How to use Generic Type in functions
I have the following structure:我有以下结构:
export interface Complex {
getId<T>(entity: T): string
}
const test: Complex = {
getId<Number>(entity){return "1"} // does not work 'entity is implicitly any'
}
Why do I have to declare the type of entity
as entity:Number
in order to make it work?为什么我必须将实体类型声明为
entity
entity:Number
才能使其工作?
Because you declare interface which has a Generic Type Function ( getById
).因为您声明了具有通用类型 Function (
getById
) 的接口。
To reference to generic as a type, you must do this:要将泛型作为一种类型引用,您必须这样做:
interface Complex<T> {
getId(entity: T): string;
}
const test: Complex<Number> = {
getId(entity) {
return entity.toString();
}
}
The use-case of what you did might be following:您所做的用例可能如下:
interface AbstractFactory {
create<T>(data: T): string;
}
const factory: AbstractFactory = {
create<T>(data: T): string {
return data.toString();
}
}
factory.create<Number>(123);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.