9

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

1 Answer 1

8

Your last try is almost correct!

let data: { [k in keyof Person]: any };
Sign up to request clarification or add additional context in comments.

1 Comment

When writing complex types, I always write let test: ReadOnly<any>; somewhere and use "Go to Type Definition" on ReadOnly to get to typescript's own types library and look at the types defined there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.