在 TypeScript 中动态覆盖接口的属性

问题描述 投票:0回答:1

有没有一种方法可以将每个属性动态包装在具有泛型类型的接口中?

我在库中定义了多个接口。 我无法修改它(例如,添加泛型)。以下接口是我在库中定义的可能接口之一的示例。

interface Original {
    a: string;
    b: number;
    c: boolean;
}

我还有这个通用类型,用于在界面中显示值。 (即,每个界面属性都有自己的 svg 图标、单位等...)我自己制作了这个通用的。

interface GenericInterface<V> {
    value: V;
    units: string;
    errorMsg?: string;
    icons: ReactElement<any>;
}

我想要做的是将

Original
界面中的每个参数用
GenericInterface
包装起来。结果如下:

interface Modified {
    a: GenericInterface<string>;
    b: GenericInterface<number>;
    c: GenericInterface<boolean>;
}

我最接近实现这一目标的方法如下:

type ModifiedGeneric<T extends object, K extends keyof T> = Record<
    K,
    GenericInterface<T[K]>
>;

type Modified = ModifiedGeneric<
    Original,
    keyof Original
>;

但这会导致所有接口参数类型的联合。即,

interface Modified {
    a: GenericInterface<string | number | boolean>;
    b: GenericInterface<string | number | boolean>;
    c: GenericInterface<string | number | boolean>;
}

有人知道我可以用来实现所需输出的解决方案吗?

typescript
1个回答
0
投票

正如 jonrsharpe 在评论中建议的那样,只需使用映射类型:

import React from 'react'

interface Original {
    a: string;
    b: number;
    c: boolean;
}

interface GenericInterface<V> {
    value: V;
    units: string;
    errorMsg?: string;
    icons: React.ReactElement<any>;
}

type ModifiedGeneric<T extends {}> = {
    [key in keyof T]: GenericInterface<T[key]>
}

type ModifiedOriginal = ModifiedGeneric<Original>

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.