Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript typescript是否有办法推断数组中不再可能有空值?_Javascript_Typescript - Fatal编程技术网

Javascript typescript是否有办法推断数组中不再可能有空值?

Javascript typescript是否有办法推断数组中不再可能有空值?,javascript,typescript,Javascript,Typescript,我有一个数组定义如下: const myArr: (MyType | null)[] = []; const myFunc = (myObj: MyType) => /* do sth */; 和一个函数,如下所示: const myArr: (MyType | null)[] = []; const myFunc = (myObj: MyType) => /* do sth */; 如果我按NOTNULL筛选myArr,然后尝试使用myFunc进行映射,则会出现编译错误,因

我有一个数组定义如下:

const myArr: (MyType | null)[] = [];
const myFunc = (myObj: MyType) => /* do sth */;
和一个函数,如下所示:

const myArr: (MyType | null)[] = [];
const myFunc = (myObj: MyType) => /* do sth */;
如果我按NOTNULL筛选myArr,然后尝试使用myFunc进行映射,则会出现编译错误,因为MyType | null不可分配给MyType。我理解为什么会发生这种情况,但这是过滤器和映射代码:

class-MyClass{
私有myArray:(字符串| null)[]=[];
myFunc=(str:string)=>str.toUpperCase();
myOtherFunc=()=>{
这个是.myArray
.filter(str=>str!==null)
.map(this.myFunc);//类型'string | null'不可分配给类型'string'。
}

}
是的,您需要一个类型防护装置

const notNullResults = this.myArray.filter((str): str is NonNullable<string> => str !== null) // string[]
const notNullResults=this.myArray.filter((str):str不可为null=>str!==null)//string[]

请注意,我们正在使用
is
运算符以及内置的泛型
不可空
类型,以指示我们只需要字符串

不可空
从类型中删除
。这里
strictNullChecks
string
无论如何都不包含null…因此
str is string
应该也可以工作,或者您可以使用通用版本,比如
const isNotNull=(值:T):value is nonnull=>!!价值观
然后简单地
myArray.filter(isNotNull)
将导致
string[]
尝试使用不可为空的选项。。我错过什么了吗?在TS 2.8中添加了一个“找不到名称‘NonNullable’”,我想,请检查您的版本。我认为您不会回避这个问题。将让TypeScript自动推断
str=>str!==null
是一种类型保护。