TypeScript 在将新创建的变量分配给新的空数组时,推断数组元素类型,

sr4lhrrt  于 9个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(149)

建议

🔍 搜索词

数组赋值推断
空数组
在创建此问题之前,您搜索的关键词列表。请将它们写在这里,以便其他人更容易地找到此建议并提供反馈。

✅ 可实现性检查清单

我的建议符合以下准则:

  • 这不会对现有的TypeScript/JavaScript代码造成破坏性的更改
  • 这不会改变现有JavaScript代码的运行时行为
  • 这可以在不根据表达式的类型发出不同的JS的情况下实现
  • 这不是一个运行时特性(例如库功能、带有JavaScript输出的非ECMAScript语法、JS的新语法糖等)
  • 此功能将与 TypeScript's Design Goals 的其他部分保持一致。

⭐ 建议

当使用 constlet 创建数组变量并将其分配给另一个类型化数组变量之后的数组时,应从变量中推断类型:

  1. class Foo {
  2. foo: number[];
  3. doSomething() {
  4. const a = this.foo = []; // a is now any[] or never[]
  5. const b: number[] = this.foo = []; // b is number[] but we have to repeat the type declaration
  6. }
  7. }

似乎存在IDE之间的不一致性,对于VS Code,它是 any[] ,而对于playground,它是 never[] 。参见 my question on StackOverflow about this

📃 激励示例

目前,如果指定 --noImplicitAny (至少对于VS和VS Code),上述代码将导致编译错误。您也没有为数组元素设置强类型变量。有了这个功能的实现,您现在可以编写:

  1. class Manager {
  2. foo: Employee[];
  3. doSomething() {
  4. const foo = this.foo = []; // a should be Employee[]
  5. for (let item of arr) { foo.push(item); }
  6. foo[0].role = "manager"; // Elements are now strongly typed.
  7. }
  8. }

💻 用例

我经常在没有像Angular这样的框架的小项目中编写HTML模板时使用这段代码。例如:

  1. export class MyComponent extends HTMLElement {
  2. // Others
  3. items: ListItem[];
  4. set(list: ListItem[]) {
  5. // This would result in error currently in VS Code with noImplicitAny
  6. const items = this.items = [];
  7. for (let item of items) {
  8. // Other code
  9. items.push(item);
  10. }
  11. // Work with items
  12. for (let item of items) {
  13. // item is any currently, not ListItem
  14. }
  15. }
  16. }
nx7onnlm

nx7onnlm1#

另外:可能是编译器选项而不是IDE负责never[]any[]之间的差异。也许只是--strictNullChecks?

owfi6suc

owfi6suc2#

是的,我可以确认这是由于那个开关引起的。在操场上,如果我取消选中那个开关,a 就会变成 any[],编译器也会抛出错误。然而,我认为这个建议仍然有效,TS应该能够从变量中推断出类型。

相关问题