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

时间:2018-01-05 16:06:20

标签: object compiler-errors typescript2.0

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?

1 个答案:

答案 0 :(得分:1)

添加?在可选的接口内的参数。像option1?: string

相关问题