To make an object type from another object type keys, you can the in
operator in combination with the keyof
operator inside an Index Signature syntax
in TypeScript.
TL;DR
// a simple type
type Person = {
name: string;
age: number;
isAdmin: boolean;
};
// make another object type from
// the `Person` type key's using the
// `in` and the `keyof` operator
// inside the `Index Signature` syntax
type AllPropertyStringPerson = {
[Value in keyof Person]: string;
};
/*
The `AllPropertyStringPerson` type content looks like this,
{
name: string;
age: string;
isAdmin: string;
}
*/
For example, let's say we have a type called Person
with some properties like name
, age
, and isAdmin
having types of string
, number
, and boolean respectively like this,
// a simple type
type Person = {
name: string;
age: number;
isAdmin: boolean;
};
Now we aim to make another object type using the Person
type's keys but with a different type for each key in the new type say string
.
To do that we can use the in
operator followed by the keyof
operator inside the Index Signature syntax like this,
// a simple type
type Person = {
name: string;
age: number;
isAdmin: boolean;
};
// make another object type from
// the `Person` type key's using the
// `in` and the `keyof` operator
// inside the `Index Signature` syntax
type AllPropertyStringPerson = {
[Value in keyof Person]: string;
};
As you can see from the above code a lot is going on. These are the explanations for the above code:
- We have used the
in
operator because we have to iterate through every property in thePerson
type - and also while looping we need to get only the key's name and for that, we have used the
keyof
operator followed by the type we need to get the key name from in our case it is thePerson
type. - The key name value will then be stored inside the
Value
placeholder name we have given inside theIndex Signature syntax
. - and finally, we have given the type of
string
for every property in the new typeAllPropertyStringPerson
.
Now if you hover over the AllPropertyStringPerson
(if you are using VScode or TypeScript enabled editor), you can see that all the keys from the Person
object are reflected in the AllPropertyStringPerson
type and all the properties are having the type of string.
It will look like this,
// a simple type
type Person = {
name: string;
age: number;
isAdmin: boolean;
};
// make another object type from
// the `Person` type key's using the
// `in` and the `keyof` operator
// inside the `Index Signature` syntax
type AllPropertyStringPerson = {
[Value in keyof Person]: string;
};
/*
The `AllPropertyStringPerson` type content looks like this,
{
name: string;
age: string;
isAdmin: string;
}
*/
We have successfully made an object type from another object type keys in TypeScript. Yay 🥳!
See the above code live in codesandbox.
That's all 😃!