![](/img/trans.png)
[英]How to make parameter conditional inside interface with generic type interface
[英]How to define a type inside a generic interface for a property inside this generic type
例子:
export interface Column<T> {
field: string;
columnFormatter?: (props: {
value: any/** field type inside T**/; data: T; node: any
}) => void;
}
field 是类型 T 内的属性的名称,我怎么能说该值是该类型?
export interface IPurchase {
id: string;
name: string;
purchaseDate: Date;
}
let doSomethingWithMyDate: (myDate: Date) => (true);
const columns: Array<Column<IPurchase>> = [
{
field: "purchaseDate", /* "purchaseDate" must be inside IPurchase */
columnFormatter: ({ value /* must identify that this is a Date */ }) =>
doSomethingWithMyDate(value)
}];
为了表示field
属性与columnFormatter
的props
参数的value
属性类型之间的相关性,您需要Column<T>
是一个联合类型,其中T
的每个键都有一个成员。 例如,给定您的IPurchase
示例,您需要Column<IPurchase>
为
type ColumnIPurchase = {
field: "id";
columnFormatter?: ((props: {
value: string;
data: IPurchase;
node: any;
}) => void);
} | {
field: "name";
columnFormatter?: ((props: {
value: string;
data: IPurchase;
node: any;
}) => void)
} | {
field: "purchaseDate";
columnFormatter?: ((props: {
value: Date;
data: IPurchase;
node: any;
}) => void);
}
这将按需要运行:
const columns: Array<Column<IPurchase>> = [
{
field: "purchaseDate",
columnFormatter: ({ value }) => doSomethingWithMyDate(value)
},
{
field: "name",
columnFormatter: ({ value }) => doSomethingWithMyDate(value) // error!
// string isn't a Date ----------------------------> ~~~~~
}
];
所以这就是我们想要的......我们如何编写Column<T>
来做到这一点?
这是一种方法:
type Column<T> = { [K in keyof T]-?: {
field: K;
columnFormatter?: (props: { value: T[K]; data: T; node: any }) => void;
} }[keyof T]
这种类型的一般形式{[K in keyof T]-?: F<K>}[keyof T]
被称为分布式对象类型,如microsoft/TypeScript#47109中所创造的; 我们在keyof T
中的键上创建一个映射类型,然后立即使用keyof T
对其进行索引,以便为 keyof T 中的每个键K
获得F<K>
的并keyof T
。
特别是在这里我们正在计算{ field: K; columnFormatter?: (props: { value: T[K]; data: T; node: any }) => void; }
{ field: K; columnFormatter?: (props: { value: T[K]; data: T; node: any }) => void; }
其中{ field: K; columnFormatter?: (props: { value: T[K]; data: T; node: any }) => void; }
是键的类型, T[K]
K
该键对应的属性值的类型。
您可以验证Column<IPurchase>
的计算结果完全符合所需的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.