BeetleJuice
BeetleJuice

Reputation: 40946

Typescript: define type with keys from other type

Suppose you have this Typescript class:

class Person {
  name: string;
  age: number;
}

How would I declare an object type that has the same properties, but any type, but for which all properties are optional? Here are some possible values that should be compatible with that type:

data = {};
data = {name: 'John'};
data = {name: anyValue};
data = {age: 'can be a string'}
data = {name: anyValue, age: null};

I'm not even sure what to search for. I've tried something like this:

let data: {(keyof Person): any};

But that does not compile

Upvotes: 9

Views: 3240

Answers (1)

Shayan Toqraee
Shayan Toqraee

Reputation: 867

Your last try is almost correct!

let data: { [k in keyof Person]: any };

Upvotes: 8

Related Questions