0

I have a function that takes an object now this object's shape can be of one of three interfaces:

interface A{ strig:string } interface B{ number:number } interface C{ boolean:boolean } 

The function takes this object an does different things depending on the shape of the object I want to do something like this

function doSomething(item: object){ if(item typeof A) do A effecst; if(item typeof B) do B effect; if(item typeof B) do C effect; } 

But I get the error "'IComic' only refers to a type, but here it is used as a value."

2
  • Type predicates Commented Oct 11, 2022 at 3:10
  • i tried this if(item is A) but i still get the error "'IComic' only refers to a type, but here it is used as a value." IComic is one of my interfaces Commented Oct 11, 2022 at 3:18

1 Answer 1

1

Let's try this out for only A first. We have the interface here:

interface A { string: string; } 

and now to check it, we have to use something similar to typeof value.string === "string". Let's return that from a function:

function isA(value: any) { // check if value is truthy first return value && typeof value.string === "string"; } 

Then we just use a type predicate:

function isA(value: any): value is A { 

You'll now be able to use it to narrow a value in an if statement (or any condition):

if (isA(aOrBOrC)) { aOrBOrC // is now type A } 
Sign up to request clarification or add additional context in comments.

1 Comment

the problem i have is im trying to do this inside a reducer swicht stament and each interface has many properties

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.