[英]Pass Element as a type in function in React/Typescript
I am trying to create a generic collection for a React project in Typescript.我正在尝试为 Typescript 中的 React 项目创建一个通用集合。 I have:
我有:
class List<T>
{
constructor(data: any){...}
}
which will create a list of a type.这将创建一个类型的列表。 I want to cast it to something by calling it with something like:
我想通过以下方式调用它来将其转换为:
let carList: List<Car> = ...
carList.cast(Car)
if assuming Car is a class.如果假设 Car 是 class。
How do I pass in a class type as a parameter to map it?如何将 class 类型作为参数传递给 map 呢? I have this so far:
到目前为止我有这个:
public cast(Type: T)
{
this.list = this.list.map(x => x as Type)
}
which does not work as the compiler complains about 'Type refers to a value but is being used as a type'.这不起作用,因为编译器抱怨“类型指的是一个值,但被用作一种类型”。 Assume this.list is created when the List is initialized.
假设 this.list 是在 List 初始化时创建的。
Type does not exists in JS runtime, so you can not pass it as function parameter. JS 运行时中不存在类型,因此不能将其作为 function 参数传递。
Usually to cast your List to List in the runtime you have to check is it possible.通常要在运行时将您的列表转换为列表,您必须检查是否有可能。 So you have to check all list content, and it could be expensive from the performance point of view
因此,您必须检查所有列表内容,从性能角度来看,这可能会很昂贵
type Guard<T> = (item: any) => item is T;
// https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
class List<T> {
constructor(
public data: T[]
) { }
static getUserGuard<T>(itemGuard: Guard<T>): Guard<List<T>> {
return (list: List<any>): list is List<T> => list.data.every(itemGuard)
}
}
// and list usage
const lists: List<any>[] = [
new List<number>([42]),
new List<string>(['foo']),
]
const isNumber = (v: any): v is number => typeof v === 'number';
const isString = (v: any): v is string => typeof v === 'string';
// some code with random lists
const doSomething = (lists: List<any>[]) => {
for (const list of lists) {
if (List.getUserGuard(isNumber)(list)) {
// list is List<number> there
} else if (List.getUserGuard(isString)(list)) {
// list is List<string> there
} else {
// list has some other type there
}
}
}
Also you can check it my classes but not by the content您也可以查看我的课程,但不能查看内容
class List<T> {
constructor(
public data: T[]
) { }
}
class NumbersList extends List<number> {
}
class StringList extends List<string> {
}
// some code with random lists
const doSomething = (lists: List<any>[]) => {
for (const list of lists) {
if (list instanceof NumbersList) {
// list is List<number> there
} else if (list instanceof StringList) {
// list is List<string> there
} else {
// list has some other type there
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.