我正在查看 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.0在 Optional 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/