Skip to content

Inferred type parameter is too narrow with strictFunctionTypes enabled and branded typesΒ #49924

Closed
@jakebailey

Description

@jakebailey

Bug Report

πŸ”Ž Search Terms

strictFunctionTypes inferred type parameter too narrow branded types

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________

⏯ Playground Link

Playground Link

πŸ’» Code

This is basically what I see in the TS repo.

export function tryCast<TOut extends TIn, TIn = any>(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut | undefined;
export function tryCast<T>(value: T, test: (value: T) => boolean): T | undefined;
export function tryCast<T>(value: T, test: (value: T) => boolean): T | undefined {
    return value !== undefined && test(value) ? value : undefined;
}

const enum SyntaxKind {
    ClassExpression,
    ClassStatement,
}

interface Node {
    kind: SyntaxKind;
}

interface Statement extends Node {
    _statementBrand: any;
}

interface ClassExpression extends Node {
    kind: SyntaxKind.ClassExpression;
}

interface ClassStatement extends Statement {
    kind: SyntaxKind.ClassStatement;
}

type ClassLike = ClassExpression | ClassStatement;

declare function isClassLike(node: Node): node is ClassLike;

declare const statement: Statement | undefined;

const maybeClassStatement = tryCast(statement, isClassLike);
const maybeClassStatement2 = tryCast<ClassLike, Node>(statement, isClassLike);

πŸ™ Actual behavior

The second type parameter to tryCast is inferred to be Statement, which is too narrow.

πŸ™‚ Expected behavior

The inferred type should be Node. This helper is used in the TS repo, but can't be used in some conditions because inference is wrong.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions