Typescript: transform required properties to optional

Typescript: transform required properties to optional



How can non-optional properties be transformed to optional ones?
Here's the code:


interface Foo
bar: any // no '?', hence this prop is required


type KeysOfFoo =
[K in keyof Foo]: any


const keysOfFoo: KeysOfFoo = // No tsc error wanted here, got: "type '' is not assignable to type KeysOfFoo"





Have a look at the Partial type: typescriptlang.org/docs/handbook/advanced-types.html
– cartant
Sep 3 at 3:51



Partial





Thanks, you gave me correct direction. I just added question mark immediately after 'key' part: [K in keyof Foo]?: any
– Nurbol Alpysbayev
Sep 3 at 3:54



[K in keyof Foo]?: any





In case it's not immediately clear from the linked document, Partial is part of TypeScript. Additionally, there is a bunch of other really useful types.
– cartant
Sep 3 at 4:10


Partial





Thanks! I got it. In my case I cannot use Partial because my value is not Foo[K], but completely different value
– Nurbol Alpysbayev
Sep 3 at 4:19



Partial


Foo[K]






Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.