Niyaz
Niyaz

Reputation: 2893

typescript keys from one interface and value as another type

I have a interface

interface User {
    firstName: string;
    secondName: string;
    age: number;
}

I wanted to create a new type with different value type

type CustomT = { regex: RegExp }
interface UserWithRegexp {
    firstName: CustomT;
    secondName: CustomT;
    age: CustomT;
}

How can i refractor the UserWithRegexp type by using the User interface

I am expecting to have something like thistype UserWithRegexp = { [key of User] : CustomT }

Upvotes: 1

Views: 28

Answers (1)

Chris Gilardi
Chris Gilardi

Reputation: 1530

How about using the Record<K, V> type?

type UserWithRegexp = Record<keyof User, CustomT>;

You should be able to use it like this.

const userWithRegex: UserWithRegexp = {
    firstName: { regex: /.*/ },
    secondName: { regex: /.*/ },
    age: { regex: /.*/ },
};

Upvotes: 1

Related Questions