简体   繁体   English

TypeScript 类型,仅强制执行 object 的属性

[英]TypeScript type that enforces only the properties of an object

Suppose I have the following:假设我有以下内容:

const myObj = { foo: 'cat', bar: 'dog', baz: 'bird' } as const;

type MyValue = 'fish' | 'bear' | 'cow';

const myValueMap: Record<string, MyValue> = {
  [myObj.foo]: 'fish',
  [myObj.bar]: 'cow',
} as const;

Because myValueMap is declared as an object with arbitrary string keys, we don't get type-checking on the actual keys of the object ( cat and dog ).因为myValueMap被声明为带有任意字符串键的 object,所以我们不会对dog cat的实际键进行类型检查。 I could remove the explicit declaration altogether, but then I don't enforce that the values are MyValue s.我可以完全删除显式声明,但是我不强制这些值是MyValue (In my actual code, MyValue is several hundred constants strings.) (在我的实际代码中, MyValue是数百个常量字符串。)

Is there a way, preferably without using a wrapper function, to enforce that values are MyValue s and still maintain the property type-checking?有没有办法,最好不使用包装器 function,强制值是MyValue并且仍然保持属性类型检查?

TS Playground TS游乐场

Maybe make use of more generics -也许使用更多的 generics -

const myValueMap: Record<myObj[keyof myObj], MyValue> = {
  [myObj.foo]: 'fish',
  [myObj.bar]: 'cow',
};

If I understood you correctly, that's how you can achieve what you require:如果我对您的理解正确,这就是您可以实现所需的方法:

const myObj = { foo: 'cat', bar: 'dog', baz: 'bird' } as const;

type MyValue = 'fish' | 'bear' | 'cow';

const myObjValue = myObj["" as keyof typeof myObj];

const myMap: Partial<Record<typeof myObjValue, MyValue>> = {
  [myObj.foo]: 'fish',
  [myObj.bar]: 'cow',
} as const;

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

相关问题 Typescript:允许泛型类型只是具有&#39;string&#39;属性的对象 - Typescript: allow a generic type to only be an object with 'string' properties TypeScript 条件类型扩展 object,仅可用属性 - TypeScript Conditional type extends object, available only properties Typescript - 声明仅具有单一类型属性的 object? - Typescript - declaring object that only has properties of a single type? 如何仅使用TypeScript声明属性为字符串类型的对象? - How to declare an object whose properties are of type string only using TypeScript? TypeScript类型,包含包含特定类型的对象的属性 - TypeScript type with properties of an object containing a specific type Typescript:将 object 属性和嵌套的 object 属性的类型更改为一种类型 - Typescript: change type of object properties and nested object properties to one type 从 Typescript 中的一个类型中只选择两个属性 - Pick only two properties from a type in Typescript 如何在TypeScript中使用动态属性定义对象的类型 - How to define type for object with dynamic properties in TypeScript 打字稿:如何为对象属性增加类型安全? - Typescript: How to add type safety to object properties? Function 类型的默认 object 属性值在 TypeScript - Function type of default object properties value in TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM