user11406
user11406

Reputation: 1258

Resolve incompatible types without casting in TypeScript?

I have a generic type (GenericType) which has a property (prop) which can contain one of two values ("thing1" | "thing2").

I also have a type (Thing1Type) in which "prop" is always "thing1". I want to check if prop = "thing1" then call a method that expects that type signature. I could cast "GenericType" to "Thing1Type", but I'm wondering if there's a better way to achieve this without casting?

Example Code:

type GenericType = {
  prop: "thing1" | "thing2"
};

type Thing1Type = {
  prop: "thing1";
};

const myObj: GenericType = { prop: "thing1" };

const myMethod = (obj: Thing1Type) => {
  console.log(obj);
}

if (myObj.prop == "thing1") {
  myMethod(myObj);
}

Upvotes: 0

Views: 102

Answers (1)

Eldar
Eldar

Reputation: 10790

Basically, you need a type guard like this:

function hasThing1(obj: GenericType): obj is {prop:"thing1"}
{
    return obj?.prop === "thing1"
}

And then you can safely call your function :

if(hasThing1(myObj)){
    myMethod(myObj)
}

Playground

Upvotes: 1

Related Questions