简体   繁体   English

TypeScript 无法在扩展语法 function 调用中推断数组类型

[英]TypeScript cannot infer array type in spread syntax function call

I can spread an array as function/constructor arguments without any problem: (test.js)我可以毫无问题地将数组作为函数/构造函数 arguments 传播:(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)但是,同样的事情在 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?这是 TypeScript 中的错误吗? It cannot figure out how to use spread syntax here.它无法弄清楚如何在这里使用传播语法。 Is there a workaround or I have to manually assign each individual argument?是否有解决方法或者我必须手动分配每个单独的参数?

Option 1:选项1:

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

Option 2:选项 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] .这将告诉 TypeScript 将a视为包含'Claire'作为其第一项和8作为其第二项的元组,这符合[string, number] Without as const a was treated as a (string | number)[] .没有as const a被视为(string | number)[]

Thank you so much.太感谢了。 Now I understand the error is due to type incompatibility.现在我明白错误是由于类型不兼容造成的。 The following code works (test.ts)以下代码有效(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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM