Andrew Jocelyn
Andrew Jocelyn

Reputation: 589

How do I initialize an empty array when using a typescript alias?

I declare a type alias but cannot initialize it without creating an item:

type ModelState = [string, string[]]; const modelState: ModelState = [null,[]]; modelState["firstName"] = ["First name is required."];

TypeScript gives me an error "Type 'undefined[]' is not assignable to type '[string, string[]]'" if I try to initialize like this:

const modelState: ModelState = [];

What is the correct way?

Upvotes: 2

Views: 7314

Answers (2)

Andrew Jocelyn
Andrew Jocelyn

Reputation: 589

Initializing like this has problems:

const modelState: ModelState = [] as any;

Try adding a key value pair:

modelState["firstName"] = ["First name is required."];

console.log(JSON.stringify(modelState));

The JSON object remains empty.

If I initialize like this and add the key/value it works as expected.

const modelState: ModelState = {};

Also typescript reports an error if the value is not an array of strings. Doesn't report a problem if the key is not a string however.

Not sure if I can say this is intuitive but it works.

Upvotes: 2

Tao
Tao

Reputation: 2240

Ideally you should initialize the tupel with data, but you can trick the compiler like this:

const modelState: ModelState = [] as any;

A tupel in in the form of [string, string[]] would still be an array with numerical index though. It looks to me that you actuall want something like this:

interface ModelState {
    firstName: string[],
    lastName: string[],
}

Or maybe even like this:

interface ModelState {
    [key: string]: string[],
}

Upvotes: 3

Related Questions