Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : how to create a typed object without passing all the properties

I have this interface:

interface Metadata {
  key: string,
  value: string,
  option1: string, // optional parameter
  option2: string, // optional parameter
  option3: string // optional parameter
}

When i try to create a typed object in this way:

const a: Metadata = {key: 'obligatory', value: 'obligatory', option1 : 'optional '};

i got this error:

error TS2322: Type '{key: 'obligatory', value: 'obligatory', option1 : 'optional '}' is not assignable to type 'Metadata'.
  Property 'option2' is missing in type '{key: 'obligatory', value: 'obligatory', option1 : 'optional '}'.

Is it possible to create an object without having to pass all the properties?

like image 507
Janka Avatar asked Dec 03 '25 20:12

Janka


1 Answers

Add a ? to your parameters inside the interface for the optional ones. Like option1?: string etc.

like image 146
RustyPiranha Avatar answered Dec 06 '25 04:12

RustyPiranha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!