Typescript Array[T] 接受 {..T} 作为有效类型

标签 typescript types

这让我在使用 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

PG

我想这是因为 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/

相关文章:

Angular2 ngFor,存在时属性未定义

Typescript 编译器 (tsc) 和相对路径

javascript - JSON.parse 有困难吗?

Azure Log Analytics - 加入失败 - 数据类型不一致

c - 在 C 中静态推断符号类型

C# : return dbnull. 值或函数的 system.type?

types - Julia:类型和数据类型之间的区别

typescript - 如何在 typescript 中选择性地从一个 Partial 分配到另一个 Partial

javascript - Ngrx 选择器不触发更新

c# - 将接口(interface) B 的实现转换为接口(interface) A 的实现