Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 832
BeetleJuice Avatar asked Oct 16 '22 05:10

BeetleJuice


1 Answers

Your last try is almost correct!

let data: { [k in keyof Person]: any };
like image 157
Shayan Toqraee Avatar answered Oct 20 '22 17:10

Shayan Toqraee