Skip to content

type-safe cast #3193

Closed
Closed
@JonathanMEdwards

Description

@JonathanMEdwards

There doesn't seem to be a safe cast in Typescript. (<T> x) does no dynamic check. This is a very common need and is provided in every other optionally and gradually typed language I know of. What is needed is something like:

function cast<T>(x: any): T {
    if (x instanceof T) return x;
    throw new Error('type cast exception');
}

except that doesn't compile. Is there an alternative solution I'm missing?

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions