To make a union type from an object index signature
key, we can use the keyof
operator followed by the index signature name in TypeScript.
TL;DR
// `Person` index signature
type Person = {
[key: string]: number;
};
// make union type from the `Person`
// index signature key type
type PersonKeys = keyof Person; // string | number
// use the `PersonKeys` union type on variables
const a: PersonKeys = "Hello"; // ✅ Valid.
const b: PersonKeys = 3; // ✅ Valid.
const c: PersonKeys = true; // ❌ Not Valid. Since it doesn't comply with `PersonKeys` union type
For example, let's say we have an index signature of an object called Person
where the keys are of string
type and the value
are of number
type like this,
// Person index signature
type Person = {
[key: string]: number;
};
NOTE: To know more about index signatures
in TypeScript, see the blog on Which type to use for objects when properties are not known ahead of time in TypeScript?
Now that we have defined the index signature called Person
, let's use the keyof
operator followed by the index signature name to create a union type from the index signature key type.
It can be done like this,
// `Person` index signature
type Person = {
[key: string]: number;
};
// make union type from the `Person`
// index signature key type
type PersonKeys = keyof Person; // string | number
As you can see from the above code the PersonKeys
is now a union type that is made of both the string and number
type.
You may also notice that even though we used only the string
type for all keys in the index signature but the union type is made of both the string
and number
type, this is because the string
type is a superset of both the string
and number
types.
Now let's use the PersonKeys
union type on variables to confirm its working.
It can be done like this,
// `Person` index signature
type Person = {
[key: string]: number;
};
// make union type from the `Person`
// index signature key type
type PersonKeys = keyof Person; // string | number
// use the `PersonKeys` union type on variables
const a: PersonKeys = "Hello"; // ✅ Valid.
const b: PersonKeys = 3; // ✅ Valid.
const c: PersonKeys = true; // ❌ Not Valid. Since it doesn't comply with the `PersonKeys` union type
As you can see that both the first 2 variables are valid since it satisfies the union type PersonKeys
and the last variable is invalid since it doesn't satisfy the PersonKeys
union type.
Yay 🥳! We have successfully made a union type from an object index signature key type in TypeScript.
See the above code live in codesandbox.
That's all 😃!