【发布时间】:2021-02-15 06:53:38
【问题描述】:
我有一个接口ColumnDef。我需要创建 2 个方法:getValue 将返回 C 类型,getComponent 将输入 arg 类型为 C。而且效果很好!
interface ColumnDef<R, C> {
getValue: (rowData: R) => C;
getComponent: (cellData: C) => ReactElement
}
然后我创建了一个数组ColumnDef。我不需要为每一列说第二种类型。 (我想使用泛型类型,比如在 java 中:ColumnDef<R, ?>[])我只需要在getValue 和getComponent 中匹配每一列的类型。我尝试使用“任何”类型,例如 ColumnDef<R, any>[];,但它破坏了类型匹配,例如以下代码:
interface ColumnDef<R> {
getValue: (rowData: R) => any;
getComponent: (cellData: any) => ReactElement
}
我想这样使用它:
const columns: ColumnDef<R, any>[] = [
{ getValue: (rowData: R) => rowData.name, getComponent: (name: string) => Label(name)},
{ getValue: (rowData: R) => rowData.size, getComponent: (size: number) => NumberBox(size)}
]
附加的最小可重现示例:
import * as React from 'react';
import { ReactElement } from 'react';
interface TestData {
name: string,
size: number
}
interface ColumnDef<R, C> {
getValue: (rowData: R) => C;
getComponent: (cellData: C) => ReactElement
}
function NumberBox(size: number): ReactElement {
return <div>{size}</div>
}
const columns: ColumnDef<TestData, any>[] = [
{ getValue: (rowData: TestData) => rowData.name, getComponent: (name: number) => NumberBox(name)}, // It is incorrect: name is not number!
{ getValue: (rowData: TestData) => rowData.size, getComponent: (size: number) => NumberBox(size)} // It is correct: size is number!
]
console.log(columns)
【问题讨论】:
-
(C: cellData) =>应该是(cellData: C) =>,我猜?理想情况下,示例代码应在 IDE 中进行测试并构成 minimal reproducible example,以便其他人可以更轻松地帮助您。 -
好的,您已经修复了那里的错误,但是您能否在minimal reproducible example 上工作,显示您打算如何创建和使用这些数组之一? TypeScript 缺乏对existential types 的直接支持(这基本上是Java 泛型中的通配符),因此您必须以某种方式解决它。
any的使用对于那些宁愿获得便利而不是严格类型安全的人来说通常已经足够了。有更安全的选择,但我想了解更多关于用例的信息,然后再用解决方案朝一个方向走得太远。 -
@jcalz 谢谢!我向问题添加了更多信息
-
const columns: ColumnDef<R, any>[]中的R是什么? minimal reproducible example 应该是我可以放入 IDE 的东西(最好是像 The TypeScript Playground 这样的独立的,看看发生了什么。如果我现在这样做,我将面临R未定义的事实,并且Label或NumberBox也不是。无论如何,我可能会回答这个问题,但如果有一些我可以实际测试的东西会很好。 -
@jcalz 感谢您的耐心等待。我添加了最小的可重现示例。
标签: reactjs typescript typescript-generics