2

I can spread an array as function/constructor arguments without any problem: (test.js)

class Person {
    name; 
    age;

    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

let a = ['Claire', 8];
let p = new Person(...a);

console.log(p);

However, the same thing doesn't work in TypeScript: (test.ts)

class Person {
    constructor(
        public name: string,
        public age: number
    ) {}
}

let a = ['Claire', 8];
let p = new Person(...a);  // Error: An argument for 'name' was not provided.

console.log(p);

Is this a bug in TypeScript? It cannot figure out how to use spread syntax here. Is there a workaround or I have to manually assign each individual argument?

0

2 Answers 2

4

Option 1:

let a: [string, number] = ['Claire', 8];

Option 2:

let a = ['Claire', 8] as const;

This will tell TypeScript to treat a as a tuple containing 'Claire' as its first item and 8 as its second which conforms to [string, number]. Without as const a was treated as a (string | number)[].

Sign up to request clarification or add additional context in comments.

3 Comments

is this different from declaring it as const a = ['Claire', 8]
@bryan60 the JavaScript result will be the same, TypeScript will treat it differently
@bryan60 const a = in that case will just tell that you won't reassign any value to this variable, it doesn't affect the type.
0

Thank you so much! Now I understand the error is due to type incompatibility. The following code works (test.ts)

class Person {
    constructor(
        public name: string,
        public age: number
    ) {}
}

/* Spell out type or use 'as const' both work!
Or TypeScript treats ['Claire', 8] as of type (string | number)[]*/
let a: [string, number] = ['Claire', 8];
let b = ['Liam', 11] as const;

let p1 = new Person(...a);
let p2 = new Person(...b);

console.log(p1, p2);

1 Comment

Please mark the original answer as correct if it led you to a solution.

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.