typescript - 强制对象包含枚举的所有键,并且仍然对其值进行类型推断

标签 typescript enums

我有一个对象,我想强制它包含一个枚举的所有键,我还想推断它的值的类型。 所以如果我这样做:

enum RequiredKeys {
    A = 'a',
    B = 'b'
}
const objectThatShouldContainAllRequiredKeys = {
    [RequiredKeys.A]: (id: string) => {}
};
// Argument of type '123' is not assignable to parameter of type 'string'
// Which is great, that's exactly what I want. 
objectThatShouldContainAllRequiredKeys[RequiredKeys.A](123);

但是现在,我尝试强制执行对象键,我尝试的每个解决方案都会破坏类型推断。例如:

enum RequiredKeys {
    A = 'a',
    B = 'b'
}
// Property 'b' is missing in type '{ a: (id: string) => void; }' but required in type 'Record<RequiredKeys, Function>'.
// Which is great, that's exactly what I want
const objectThatShouldContainAllRequiredKeys: Record<RequiredKeys, Function> = {
    [RequiredKeys.A]: (id: string) => {}
};
// No error here, which is less great...
objectThatShouldContainAllRequiredKeys[RequiredKeys.A](123);

知道如何享受两个世界吗?对象是否强制执行枚举中的所有键并推断对象值? 谢谢!!

最佳答案

您可以创建带有类型参数的标识函数,将类型参数限制为具有所需的键,因此 typescript 将验证传递的对象键并推断其值的类型:

const createWithRequiredKeys = <T extends Record<RequiredKeys, unknown>>(obj: T) => obj;

const withRequiredKeys = createWithRequiredKeys({
    [RequiredKeys.A]: (id: string) => {},
    [RequiredKeys.B]: 'foo',
}); 

// withRequiredKeys is { a: (id: string) => void; b: string; }

withRequiredKeys[RequiredKeys.A](123); // 'number' is not assignable to parameter of type 'string'

Playground

关于typescript - 强制对象包含枚举的所有键,并且仍然对其值进行类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65233206/

相关文章:

c# - 如何将具有描述属性的枚举转换为字典?

c# - 流畅的 nhibernate 字符串到枚举选择查询示例

javascript - Angular 8拖放dragover Dragleave事件未触发

javascript - 转译为 es5 时 Jquery 不起作用

mongodb - 使用 Typescript 和 Mongodb 应该如何定义文档的接口(interface)?

java - 我可以根据其字段的值获取枚举吗?

Objective-C - 定义一个枚举,可以像 ENUMTYPE.ENUMVAL 一样调用

c - 在 C 中读取和转换枚举类型

typescript - Typescript 推断的对象字面量类型扩展是如何工作的?

typescript - TS4.1 : Is there a way to define this property path type that isn't excessively deep?