Skip to content

prefer-native-coercion-functions should ignore type guards #1857

Open
@JacobLey

Description

@JacobLey

prefer-native-coercion-functions is used to simplify methods like filter that are simply trying to find truthy values. However the native type castings do not provide any typescript assertions, so the resulting type of the filter is unchanged. When manually providing these assertions, prefer-native-coercion-functions should not suggest a native coercion over the manual callback.

prefer-native-coercion-functions

const mixedData: (string | null)[] = ['abc', '', null, 'xyz'];

// Eslint is happy, but `null` is not removed from type
const untypedMixedData: (string | null)[] = mixedData.filter(Boolean);

// Eslint is unhappy, but `null` is removed from type
const typedMixedData: string[] = mixedData.filter((d): d is string => Boolean(d));

Ideally that second example is ignored by this eslint rule because the custom assertions provide context that the native coercion function does not.


Alternatively the resulting array can just be manually typed casted, but I would argue that typescript's default typings via assertions is preferred.

const castMixedData: string[] = mixedData.filter(Boolean) as string[];

Similarly I could provide some method like isTruthy

const isTruthy = (x: unknown): x is string | number | symbol | object | unknown[] => Boolean(x);
const isTruthyData = mixedData.filter(isTruthy);

but that will interfere with no-array-callback-reference.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions