Skip to content

ReturnType support for assertions #34636

Closed
@sirian

Description

@sirian

Suggestion

Not found a way to provide return type for assert function. Look at use case

Use Cases

function assert1(e: any, m?: string): asserts e {
    if (!e) throw new Error();
    return e;
}
function assert2<T>(e: T, m?: string): asserts e {
    if (!e) throw new Error();
    return e; // error:  T is not assignable to void
}

declare const p: Promise<string | undefined>;
p.then(assert1).then((x) => x.length); // error: x is string | undefined
p.then(assert2).then((x) => x.length
); // error: x is string | undefined

This doesn't work also

const assertAndReturn = <T>(x: T) => { 
    assert(x);
    return x;
}
p.then((x) => { assert(x); return x; }).then((x) => x.length) // ok
p.then(assertAndReturn).then((x) => x.length); // error. x is string | undefined

Playground

Related issues

#34596

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions