I have the following interface in TypeScript:

interface IX {
    a: string,
    b: any,
    c: AnotherType
}

I declare a variable of that type and I initialize all the properties

let x: IX = {
    a: 'abc',
    b: null,
    c: null
}

Then I assign real values to them in an init function later

x.a="xyz"
x.b = 123
x.c = new AnotherType()

But I don’t like having to specify a bunch of default null values for each property when declaring the object when they’re going to just be set later to real values. Can I tell the interface to default the properties I don’t supply to null? What would let me do this:

let x: IX = {
    a: 'abc'
}

without getting a compiler error. Right now it tells me

TS2322: Type ‘{}’ is not assignable to type
‘IX’. Property ‘b’ is missing in type ‘{}’.

16 Answers
16

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *