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?
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. ...
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.
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 () ?
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.
The
in
operator returnstrue
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With