如何在打字稿中使用不同类型的通用键键入对象 [英] How to type an object with generic keys of different types in typescript

查看:25
本文介绍了如何在打字稿中使用不同类型的通用键键入对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你会如何在打字稿中输入这个对象?

How would you type this objects in typescript ?

我有一个特殊的日期时间"键是日期,其余键是数字.但我事先不知道将在每个对象上设置哪些键.示例值:

I have one special "datetime" key that is a Date, the rest of the keys are numbers. But I don't know in advance which keys will be set on each object. Examples values:

type Metrics = ??????

const example1: Metrics = {
  datetime: new Date(),
  activity: 12.34,
  min: 12.34,
  max: 12.34,
}
const example2: Metrics = {
  datetime: new Date(),
  avg: 12.34,
}

这是我尝试过的:

type Metrics = {
  datetime: Date,
  [key: string]: number,
}
// ERROR on the type definition:
// Property 'datetime' of type 'Date' is not assignable to string index type 'number'


type Metrics = { 
    datetime: Date 
} & {  
    [key: string]: number 
}
// ERROR on the variable assignment:
// Type '{ datetime: Date; activity: number; min: number; max: number; }' is not assignable to type 'Metrics'.
//   Type '{ datetime: Date; activity: number; min: number; max: number; }' is not assignable to type '{ [key: string]: number | null; }'.
//     Property 'datetime' is incompatible with index signature.
//       Type 'Date' is not assignable to type 'number'.

推荐答案

你会想要一些使用 Record, number> 来映射所有当前键的东西键入数字但排除键日期时间".由于这对于通常的索引类型不一定可行,因此您最好使用将类型限制为泛型的辅助函数:

You will want something that uses Record<Exclude<K,"datetime">, number> to map all present keys to type number but exclude the key "datetime". Since this won't necessarily be possible with a usual index type you are probably best off using a helper function that constrains the type as a generic:

type Metrics<K extends keyof any> = { datetime: Date } & Record<Exclude<K, "datetime">, number>;

function makeMetrics<T extends Metrics<keyof T>>(metrics: T): T {
    return metrics;
}

const example1 = makeMetrics({
    datetime: new Date(),
    activity: 12.34,
    min: 12.34,
    max: 12.34,
});
const example2 = makeMetrics({
    datetime: new Date(),
    avg: 12.34,
});

这意味着两个示例都将只允许定义时存在的键,稍后添加额外的键则不会,以便您需要诸如除datetime之外的所有键是数字"据我所知,这是不可能的.

This means that both examples will only allow the keys that are present when it is defined, adding extra keys later would not, in order to allow that you'd need something like "all keys except datetime are numbers" which is not possible as far as I know.

这篇关于如何在打字稿中使用不同类型的通用键键入对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆