如何根据过滤器推断使打字稿限制数组类型?

How can I make typescript restrict array type based on filter inference?

这将永远不会失败 return 一个字符串数组:

(arr: (string | undefined)[]): string[] => arr.filter(item => item !== undefined);

playground link

但是 TypeScript 不接受编译它,因为它不推断过滤器谓词将 return true 当且仅当 item 是一个字符串。显式输入谓词似乎也无济于事:

const predicate = (item: string | undefined): item is string => item !== undefined;
(arr: (string | undefined)[]): string[] => arr.filter(item => predicate(item));

playground link

这行得通,但更冗长(如果我没记错的话,速度要慢得多):

(arr: (string | undefined)[]): string[] => {
    const ret: string[] = [];
    for (const item of arr) {
        if (item !== undefined) {
            ret.push(item);
        }
    }
    return ret;
}

playground link

我是否可以在我的 tsconfig.json 中启用一个实验性标志,使 TypeScript 能够根据 .filer 谓词进行类型推断?

您正在使用匿名内联函数而不是谓词:

TS Playground link

const predicate = (item: string | undefined): item is string => item !== undefined;

(arr: (string | undefined)[]): string[] => arr.filter(item => predicate(item)); // error

(arr: (string | undefined)[]): string[] => arr.filter(predicate); // ok

// inline predicate
(arr: (string | undefined)[]): string[] => arr.filter((item): item is string => item !== undefined);