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."
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.