Search code examples
typescripttypechecking

Checking whether a parameter belongs to a type in Typescript


How can I check whether a certain parameter belongs to a type I've defined in TypeScript? For example:

type myType = {n:number}
let par = {n:3}

I want to check whether x is of the type mtType. If I use typeof par the returned value of it is the string "object". Thanks.


Solution

  • Take a look at the type guards section here. It is possible with the following syntax:

    function isMyType(arg: any): arg is myType {
        // you can replace the following expression with the logic 
        // that clearly defines that if an object can be myType
        return arg.n !== undefined && arg.n === parseInt(arg.n);
    }
    

    and later in the code

    if (isMyType(objectToCheck)){
       // do something with the object as myType
    }