[英]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:根据您的需要,您可以自动构建您的类型:
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"
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"
the AllKeys
type is just for convenience, you can inline it and use Exclude<keyof typeof obj, "d">
AllKeys
类型只是为了方便起见,您可以内联它并使用Exclude<keyof typeof obj, "d">
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"
Again, the two types AllKeys
and AllowedKeys
are here for convenience.同样,为了方便起见,这里有两种类型的
AllKeys
和AllowedKeys
。 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.