To make a union type
from another object's type, we can use the keyof
operator followed by the object's type name in Typescript.
TL;DR
// Person type alias
type Person = {
name: string;
age: string;
salary: string;
userType: string;
};
// make union type from
// `Person` type alias
// using the `keyof` operator
type PersonKeys = keyof Person; // "name" | "age" | "salary" | "userType"
// make a variable and use the `PersonKeys` as its type
let john: PersonKeys = "age"; // ✅ Valid.
john = "hello"; // ❌ Invalid.
For example, let's say we have a type alias called Person
with 4 properties called name
, age
, salary
, and userType
all having the type of string
like this,
// Person type alias
type Person = {
name: string;
age: string;
salary: string;
userType: string;
};
Now to make a union type
using the object's type Person
, first let's make a type alias
called PersonKeys
and then use the keyof
operator followed by the type alias name, in our case, it is the Person
.
It can be done like this,
// Person type alias
type Person = {
name: string;
age: string;
salary: string;
userType: string;
};
// make union type from
// `Person` type alias
// using the `keyof` operator
type PersonKeys = keyof Person; // "name" | "age" | "salary" | "userType"
Now to prove that our PersonKeys
union type is working let's use the PersonKeys
as a type for a variable called john
like this,
// Person type alias
type Person = {
name: string;
age: string;
salary: string;
userType: string;
};
// make union type from
// `Person` type alias
// using the `keyof` operator
type PersonKeys = keyof Person; // "name" | "age" | "salary" | "userType"
// make a variable and use the `PersonKeys` as its type
let john: PersonKeys = "age"; // ✅ Valid.
john = "hello"; // ❌ Invalid.
As you can see from the above code that assigning a value of age
is valid because it is one of the union types from the PersonKeys
union type and assigning the value of hello
is invalid since it doesn't satisfy the PersonKeys
union type.
Yay, we have successfully made a union type from another object's type. 🥳
See the above code live in codesandbox.
That's all 😃!