generics - typescript 泛型类型和未定义

标签 generics typescript immutable.js

我正在查看 facebook 的不可变库及其 typescript 绑定(bind)。

如果我有这个代码:

const list: User[] = ...;
list.map(user => ...)

lambda 参数的类型 user是正确的 User .

但是,如果我导入不可变的 List并包装我的数组:
import {Map, List} from "immutable";
List(list).map(user => ...)

现在,让我感到困惑的是 lambda 参数 user推断为 User | undefined .甚至将电话更改为 List<User>(list)没有帮助。

查看库的 .d.ts,定义是:
export function List<T>(array: Array<T>): List<T>;

所以我不明白这里发生了什么?

最佳答案

原因写在What's new in TypeScript 2.0Optional parameters and properties部分:

Optional parameters and properties automatically have undefined added to their types, even when their type annotations don't specifically include undefined. For example, the following two types are identical:


// Compiled with --strictNullChecks
type T1 = (x?: number) => string;              // x has type number | undefined
type T2 = (x?: number | undefined) => string;  // x has type number | undefined

编辑

immutable.js 的定义文件改变了,现在如果你看 the map method 的签名它看起来像这样:
map<M>(
    mapper: (value: V, key: K, iter: /*this*/Iterable<K, V>) => M,
    context?: any
): /*this*/Iterable<K, M>;

但是如果你去a commit before that它看起来像这样:
map<M>(
    mapper: (value?: V, key?: K, iter?: /*this*/Iterable<K, V>) => M,
    context?: any
): /*this*/Iterable<K, M>;

这里是 value是可选的。

如果您更新定义文件,它将被修复。

关于generics - typescript 泛型类型和未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41070021/

相关文章:

java - 参数化参数化方法的返回类型

typescript - typescript 中的装饰器返回函数的时间

angular - 当其中之一具有异步管道时,如何在两个条件下实现 和 ngif

javascript - 如何在不可变对象(immutable对象)的函数式 JavaScript 转换中处理 if/else 以进行调试

javascript - Redux + ImmutableJS - 如何垃圾收集太大的商店?

javascript - 如何从不可变树中获取更改的树,最大限度地重用节点

java - 什么是 PECS(生产者扩展消费者 super )?

去泛型 : infer type parameter for variadic function with zero arguments

c# - 在 C# 中返回 'this' 的数组

javascript - 如何在 TSX 中将值从子组件传递给父组件?