Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Type guards: Using the in operator

Tags:

typescript

I'm learning TypeScript and practicing about Type Guards from Official DOCS

I'm testing the provided example (more or less) with TypeScript 3.5.3:

function exec(strOrNum: string | number) {
    if ("substring" in strOrNum) {
        return strOrNum.substring(1);
    }
    return strOrNum.toExponential(2);
}

But VSCode is trowing the following error:

The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)

I don't understand it, any idea?

like image 847
Rafa Romero Avatar asked Aug 21 '19 15:08

Rafa Romero


People also ask

How to use type guards in typescript?

TypeScript Type Guards 1 typeof. Both arguments must be either numbers or strings.' First, define the alphanumeric type that can hold either a string or a number. 2 instanceof. Similar to the typeof operator, TypeScript is also aware of the usage of the instanceof operator. ... 3 in. ... 4 User-defined Type Guards. ...

What are type guards and type assertions in TS?

Type guards “guard” a block of code from unwanted types. As with all things, there are several ways to use type guards. Type assertions are similar to “casts” in other languages. They’re a way for us to tell the TS compiler that we know more than it does, and “assert” that a given entity is a certain type.

What is the use of in operator in JavaScript?

The in operator carries a safe check for the existence of a property on an object. You can also use it as a type guard. For example: function signContract(partner: BusinessPartner) : string { let message: string ; if ( 'isCreditAllowed' in partner) { message = partner.isCreditAllowed () ?

How to define a custom type guard in C++?

To define a custom type guard, we need to write a function whose return type is a type predicate. A type predicate looks like propertyName is Type. Where propertyName (Must be the name of the function parameter) is of type Type. If the function returns true, it indicates that propertyName is Type is true.


1 Answers

The in operator returns true if the specified property is in the specified object or its prototype chain.

This means it operates on objects (or arrays) and not strings.

If you want to add a type guard to differentiate between string and number you have to use typeof:

function exec(strOrNum: string | number) {
    if (typeof strOrNum === "string") {
        return strOrNum.substring(1);
    }
    return strOrNum.toExponential(2);
}

You would use the in operator if you have a union of two interfaces:

interface A {
    a: string;
}

interface B {
    b: number;
}


function test(arg: A | B): string {
    if ('a' in arg) {
        return arg.a;
    }
    return arg.b.toFixed(2);
}

like image 192
ChrisG Avatar answered Sep 23 '22 21:09

ChrisG