简体   繁体   English

确保字符串文字联合属于对象的键

[英]Make sure a string literal union belongs to an object's keys

export type A = "a" | "b" | "c";

const obj = { a: 4, b: 5, c: 6, d: 7 };

How do I make sure all elements of A are keys of object obj ?如何确保A所有元素都是对象obj键?

Depends on what you need, you can automatically construct your type:根据您的需要,您可以自动构建您的类型:

All keys as a type所有键作为一种类型

You can use keyof to have all the keys as a union.您可以使用keyof将所有键作为联合。 Since keyof needs to be used on a type, the keyof typeof obj :由于keyof需要对一种类型的所使用的, keyof typeof obj

const obj = { a: 4, b: 5, c: 6, d: 7 };

export type A = keyof typeof obj; // "a" | "b" | "c" | "d"

Playground Link 游乐场链接

Remove some of the keys删除一些键

You can then Exclude some of the keys and get the rest:然后,您可以Exclude一些键并获取其余键:

const obj = { a: 4, b: 5, c: 6, d: 7 };
type AllKeys = keyof typeof obj;
export type A = Exclude<AllKeys, "d">; // "a" | "b" | "c" 

Playground Link 游乐场链接

the AllKeys type is just for convenience, you can inline it and use Exclude<keyof typeof obj, "d"> AllKeys类型只是为了方便起见,您可以内联它并使用Exclude<keyof typeof obj, "d">

Only allow some of the keys只允许某些键

This would be sort of the opposite of Exclude - instead of blacklisting keys, you have a whitelist and only pick keys that exist in it using an intersection :这与Exclude有点相反 - 您有一个白名单,而不是将键列入黑名单,并且只使用交叉点选择其中存在的键:

const obj = { a: 4, b: 5, c: 6, d: 7 };
type AllKeys = keyof typeof obj;
type AllowedKeys = "a" | "b" | "c" | "y" | "z";
export type A = AllKeys & AllowedKeys; // "a" | "b" | "c"

Playground Link 游乐场链接

Again, the two types AllKeys and AllowedKeys are here for convenience.同样,为了方便起见,这里有两种类型的AllKeysAllowedKeys You can also have the same as keyof typeof obj & ("a" | "b" | "c" | "y" | "z");你也可以有同样的keyof typeof obj & ("a" | "b" | "c" | "y" | "z");

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

相关问题 确保对象键属于定义的集合 - Make sure object key belongs to a defined set 如何从 TS 文字联合类型推断 object 的键和值? - How to infer keys and values of an object from TS literal union type? 访问对象中的可选键,其中键是文字联合类型中的文字,没有错误“对象可能是‘未定义’” - Access optional keys in object, where key is a literal in a literal union type without error "Object is possibly 'undefined'" 从 object 个键中检索推断的字符串文字 - Retrieve inferred string literal from object keys 有没有办法从 Typescript 和 object 创建字符串文字联合类型? - Is there a way to create string literal union type from and object in Typescript? TypeScript:返回输入字符串数组的文字值的联合? - TypeScript: return a union of the input string array's literal values? Typescript 从 object 中的数组创建字符串文字联合类型 - Typescript create string literal union type from array in object 将字符串缩小为字符串文字并集 - Narrowing string to string literal union 为什么在对象文字中赋值时 TypeScript 将字符串文字联合类型转换为字符串? - why is TypeScript converting string literal union type to string when assigning in object literal? 另一个联合类型中的打字稿联合字符串文字 - Typescript union string literal in another union type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM