2

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?

2 Answers 2

3

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[],
}
Sign up to request clarification or add additional context in comments.

1 Comment

const modelState: ModelState = [] as any; should solve the issue.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.