首页 > 解决方案 > 在数组的过滤方法之后指定所需的类型

问题描述

我想在两个数组之间进行分隔。在一个数组中,对象没有特定值。另一方面,它应该有一个字符串。

interface Relation<T> {
  href: URL;
  notAlways: T;
}

// This response sometimes has a string or a null value in the 'notAlways' key.
const response: { relations: Relation<string | null>[] } = await request(paramUrl);

const doesNotHaveIt: Relation<null>[] = response.relations.filter(
  (relation: Relation<string | null>) => !relation.notAlways,
);
// Error: Type 'Relation<string | null>' is not assignable to type 'Relation<null>

const doesHaveIt: Relation<string> = response.relations.filter(
  (relation: Relation<string | null>) => relation.notAlways
);
// Error: Type 'Relation<string | null>' is not assignable to type 'Relation<string>'.

标签: typescript

解决方案


您可以使谓词(传递给filter类型保护

const doesNotHaveIt: Relation<null>[] = response.relations.filter(
    (relation: Relation<string | null>): relation is Relation<null> => !relation.notAlways,
);

const doesHaveIt: Relation<string>[] = response.relations.filter(
    (relation: Relation<string | null>): relation is Relation<string> => !!relation.notAlways
);

操场


现在可以删除显式变量注释,因为它已正确推断:

const doesNotHaveIt = response.relations.filter(
    (relation: Relation<string | null>): relation is Relation<null> => !relation.notAlways,
); // doesNotHaveIt is Relation<null>[]

推荐阅读