打字稿界面对象键

时间:2021-06-01 06:28:30

标签: typescript interface

在打字稿中如何从另一个接口键创建键值对数组的接口。

typescriptlang sandbox

A 有下一个接口:

type KeyValue<K, V> = {
    key: K;
    value: V;
};

interface Features {
    wheels: number;
    color: string;
    packages?: string[];
}

interface Car {
    manufacturer: string;
    model: string;
    features: Features;
}

接下来,使用这个接口创建变量:

const fordFocus: Car = {
    manufacturer: "ford",
    model: "focus",
    features: {
        wheels: 17,
        color: "white",
    },
};

const bmwX3: Car = {
    manufacturer: "bmw",
    model: "X3",
    features: {
        wheels: 19,
        color: "black",
        packages: ["S08SM", "S08TF", "S08TG", "S0925"],
    },
};

我想将此变量发送到服务器。

请求数据应该有下一个架构:

interface CarRequest {
    manufacturer: string;
    model: string;
    features?: {key: string, value: any}[]
}

现在我手动声明功能,但我想通过实用程序接口来完成。 像这样:

interface FeaturesRequest<T, K in T> {
  [n: number]: {key: K, value: T}
}

准备请求数据的函数

function prepareCarRequest(car: Car) {
    const request: CarRequest = {
        manufacturer: car.manufacturer,
        model: car.model,
        features: Object.entries(car.features).map(([key, value]) => ({key, value})),
    };

    return request;
}

我不明白我应该如何声明 requestData 以便它在 Feature 接口中选择键并自动将其转换为 KeyValue。

1 个答案:

答案 0 :(得分:0)

您可以使用相当简单的 mapped type 将您的界面转换为键值类型:

type InterfaceToKV<T> = {
    [K in keyof T]: { key: K, value: T[K] }
}[keyof T]

TS playground

但是 Object.entries' 类型是 more generic(讨论是关于 Object.keys 但同样适用于 Object.entries)并且不允许您分配 string到您的关键文字类型。