Search code examples
typescript

Typescript interface default values


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


Solution

  • Can I tell the interface to default the properties I don't supply to null? What would let me do this

    No. You cannot provide default values for interfaces or type aliases as they are compile time only and default values need runtime support

    Alternative

    But values that are not specified default to undefined in JavaScript runtimes. So you can mark them as optional:

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

    And now when you create it you only need to provide a:

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

    You can provide the values as needed:

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