Typescript interface default values

d512 picture d512 · Jan 29, 2016 · Viewed 245.3k times · Source

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 '{}'.

Answer

Timar picture Timar · Apr 5, 2017

You can't set default values in an interface, but you can accomplish what you want to do by using Optional Properties (compare paragraph #3):

https://www.typescriptlang.org/docs/handbook/interfaces.html

Simply change the interface to:

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

You can then do:

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

And use your init function to assign default values to x.b and x.c if those properies are not set.