问题描述
当我使用 useState<Options[]>
作为反应钩子时,当我错误地输入 {...options}
而不是 [ 时,这让我感到困惑...options]
,我只是在尝试访问数组"(对象)的 .map
并得到 TypeError 时才发现.让我举个例子来说明我的问题:
This bit me when using useState<Options[]>
as a react hook, when I mistyped {...options}
instead of [...options]
, I only found out when I tried to access .map
of "array" (object) and got a TypeError. Let me give you an example that can clarify my question:
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 本身的问题:
This appears to be indeed a problem with Typescript itself:
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
此外,这也会在运行时编译和中断:
Moreover, this also compiles and breaks at run-time:
class E {
method() { }
}
let e: E = Object.assign({}, new E)
e.method() // runtime error
我猜这是因为 Object.assign
被声明为
I guess this is because Object.assign
is declared as
assign<T, U>(target: T, source: U): T & U;
这是不正确的,因为 assign
返回的内容实际上并没有扩展 U
.assign
的返回类型应该类似于 T &OwnProperties
,但目前无法实现,请参阅
which is incorrect, since what assign
returns doesn't actually extend U
. The return type of assign
should be something like T & OwnProperties<U>
, but this is currently not possible, see
- https://github.com/microsoft/TypeScript/issues/28801
- https://github.com/microsoft/TypeScript/issues/9726
这篇关于Typescript Array[T] 接受 {..T} 作为有效类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!