typescript扩展到未定义的并集
我将Immutable.js与Typescript一起使用;我在编译TypeScript时启用了-strict选项,现在出现了一个有趣的错误 我有以下代码:typescript扩展到未定义的并集,typescript,immutable.js,Typescript,Immutable.js,我将Immutable.js与Typescript一起使用;我在编译TypeScript时启用了-strict选项,现在出现了一个有趣的错误 我有以下代码: import { Map } from "immutable"; class MyClass { public readonly map: Map<string, MyTypeA> public removeFromMap(keys: Seq.Indexed<string>): MyClass {
import { Map } from "immutable";
class MyClass {
public readonly map: Map<string, MyTypeA>
public removeFromMap(keys: Seq.Indexed<string>): MyClass {
const newMap = keys.reduce((r: Map<string, MyTypeA>, v: string, k: number) => {
return r.remove(v);
}, this.map);
...
}
}
类型为“r:Map,v:string,k:number=>Map”的参数不能分配给类型为“reduce?”:Map |未定义,value?:string |未定义,key?:number |未定义,iter?:Iterable |未定义=>Map”的参数。
参数“r”和“reduce”的类型不兼容。
类型“Map | undefined”不可分配给类型“Map”。
类型“undefined”不可分配给类型“Map”
我可以通过将代码更改为来解决此错误
import { Map } from "immutable";
class MyClass {
public readonly map: Map<string, MyTypeA>
public removeFromMap(keys: Seq.Indexed<string>): MyClass {
const newMap = keys.reduce((r: Map<string, MyTypeA> | undefined, v: string | undefined, k: number | undefined) => {
return r!.remove(v!);
}, this.map);
...
}
}
但这是难以置信的冗长。在这种情况下,为什么严格模式下的TypeScript不能识别string类型也是string | undefined类型?我相信这种类型的扩展会发生在我的代码库的其他区域,但由于某些原因,它不会发生在这里
有没有一种方法可以以不太冗长的方式在-strict模式下解决此错误
我相信这种类型的扩展会发生在我的代码库的其他区域,但由于某些原因,它不会发生在这里
当它发生时
当它安全的时候
declare var str: string;
declare var strOrUndef: string | undefined;
strOrUndef = str; // OKAY
当它没有发生的时候
当它不安全的时候!您的代码已简化:
function iTakeFunctionThatIWillCallWithUndefined(
fun: (hehe: string | undefined) => void
){
fun(undefined);
}
iTakeFunctionThatIWillCallWithUndefined(function(str: string){ // Error
// I expect it to be a string
})
您传递给reduce的回调的参数类型不是推断出来的吗?我根本不会具体说明它们是推断出来的,我不知道这一点;因此,我可以完全删除所有类型注释,并传递keys.reducer、v、\ux。但这让代码变得不那么清晰;对于函数型脚本来说,这会被认为是惯用的和直观的吗?我在这里看到人们到处指定所有类型,但这不是标准。就我个人而言,我的观点是让编译器尽可能地推断所有参数。你不需要所有参数,如果最后一个参数没有使用,你可以删除它们,参数较少的函数仍然与回调兼容