简体   繁体   English

Typescript 接口 object 按键

[英]Typescript interface object keys

How in typescript create interface of array of key value pair from another interface keys.如何在 typescript 中从另一个接口键创建键值对数组接口。

typescriptlang sandbox typescriptlang 沙箱

A have next interfaces: 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;
}

Next, create variables using this interfaces:接下来,使用此接口创建变量:

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"],
    },
};

I want to send this variables to server.我想将此变量发送到服务器。

Request data should have next schema:请求数据应该有下一个模式:

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

Now i declare features manually, but i want to do it by utility interface.现在我手动声明功能,但我想通过实用程序界面来做。 Like this:像这样:

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

Function that prepare request data Function 准备请求数据

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;
}

I don't understand how i should declare requestData that it pick keys in Feature interface and transform it to KeyValue automatically.我不明白我应该如何声明它在 Feature 接口中选择键并将其自动转换为 KeyValue 的 requestData。

You can transform your interface into key-value type with a rather simple mapped type :您可以使用相当简单的映射类型将您的界面转换为键值类型

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

TS playground TS游乐场

But the Object.entries ' type is more generic (discussion is about Object.keys but the same applies to Object.entries ) and will not allow you to assign string to your key literal types.但是Object.entries的类型更通用(讨论是关于Object.keys但同样适用于Object.entries的类型)并且不允许您分配string类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM