[英]typescript generic type and undefined
我正在查看Facebook的不可變庫及其打字稿綁定。
如果我有此代碼:
const list: User[] = ...;
list.map(user => ...)
lambda參數user
的類型正確為User
。
但是,如果導入不可變的List
並包裝數組:
import {Map, List} from "immutable";
List(list).map(user => ...)
現在,令我感到困惑的是,lambda參數user
被推斷為User | undefined
User | undefined
。 即使將調用更改為List<User>(list)
也無濟於事。
查看該庫的.d.ts,其定義為:
export function List<T>(array: Array<T>): List<T>;
所以我不明白這里發生了什么?
原因是在TypeScript 2.0的新增功能的“ 可選參數和屬性”部分中編寫的:
可選參數和屬性會自動將未定義添加到其類型中,即使它們的類型注釋未明確包含未定義也是如此。 例如,以下兩種類型是相同的:
// 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的定義文件已更改,現在,如果您查看map方法的簽名, 則它看起來像這樣:
map<M>(
mapper: (value: V, key: K, iter: /*this*/Iterable<K, V>) => M,
context?: any
): /*this*/Iterable<K, M>;
map<M>(
mapper: (value?: V, key?: K, iter?: /*this*/Iterable<K, V>) => M,
context?: any
): /*this*/Iterable<K, M>;
這里的value
是可選的。
如果更新定義文件,它將被修復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.