Without more information on your use case, I'm not sure what's the best way for you to go. You can use string enums:
export enum MyKey {
MYKEY_NOT_ALL_SPECIFIED = 'MYKEY_NOT_ALL_SPECIFIED', // no <any>
OTHERKEY = 'OTHERKEY',
ETC = 'ETC'
}
class Something {
checkKey: MyKey;
someMethod() {
if (this.checkKey === MyKey.MYKEY_NOT_ALL_SPECIFIED) {
// do something
}
}
}
Or, if you don't want to repeat yourself and know that the values and keys will always be equal, you can just use a constant plain object:
function sameValuesAsKeys<K extends string>(...values: K[]): {readonly [P in K]: P} {
const ret = {} as {[P in K]: P}
values.forEach(k => ret[k] = k);
return ret;
}
export const MyKey = sameValuesAsKeys('MYKEY_NOT_ALL_SPECIFIED', "OTHERKEY", "ETC");
type MyKey = keyof typeof MyKey;
// still works
class Something {
checkKey: MyKey;
someMethod() {
if (this.checkKey === MyKey.MYKEY_NOT_ALL_SPECIFIED) {
// do something
}
}
}
Does that answer your question? If not, please be more specific about your use case... show some code where you can't get the key you want or where you feel like you're repeating yourself, and I'll update the answer.
Hope that helps; good luck!
Update 1
Explaining the signature of
function sameValuesAsKeys<K extends string>(...values: K[]): {readonly [P in K]: P}
The type parameter K
is some string or union of strings, and the parameter values
is an array of that type of string. If I call sameValuesAsKeys("dog","cat")
, TypeScript infers K
to be "dog"|"cat"
. The return type of sameValuesAsKeys()
is {readonly [P in K]: P}
which is a mapped type meaning roughly "an object where each property is readonly and where the value is the same as the key". So if I call sameValuesAsKeys("dog","cat")
, the return value is of type {readonly dog: "dog"; readonly cat: "cat"}
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…