这让我在使用 useState<Options[]>
时很不爽作为 react 钩子(Hook),当我输入错误时 {...options}
而不是 [...options]
,我只是在尝试访问 .map
时才发现“数组”(对象)的并得到一个 TypeError。让我举个例子来澄清我的问题:
interface Option {
title: string;
isSelected?: boolean;
}
function myFunc(options: Option[]): void {}
const options: Option[] = [{title: 'Male', isSelected: true}, {title: 'Female'}, {title: 'Other'}];
const options2 = {...options};
myFunc(options);
myFunc(options2); // why isn't this an error ?
最佳答案
这似乎确实是 Typescript 本身的问题:
let c: number[] = { ...[0, 1, 2] }; // compiles
c.fill(0) // runtime error
let d: number[] = Object.assign({}, [0, 1, 2]); // compiles
d.fill(0) // runtime error
此外,这也会在运行时编译和中断:
class E {
method() { }
}
let e: E = Object.assign({}, new E)
e.method() // runtime error
我想这是因为 Object.assign
声明为
assign<T, U>(target: T, source: U): T & U;
这是不正确的,因为 assign
返回实际上并没有扩展 U
. assign
的返回类型应该类似于 T & OwnProperties<U>
, 但目前这是不可能的,请参阅
关于Typescript Array[T] 接受 {..T} 作为有效类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58374699/