32
loading...
This website collects cookies to deliver better user experience
any
type and instead use the unknown
type, which you can read here. In this article, I want to focus on Type assertion and why you should avoid them. as
syntax or the angle bracket <Type>
syntax, as shown below:type Person = {
firstname: string;
lastname: string;
}
// using as syntax
const x : unknown = {};
// asserting it as Person using as syntax
const firstname = (x as Person).firstname;
// asserting it as Person using the angle brackets
const firstname = (<Person>x).firstname;
x
has the property firstname
we are accessing because we are asserting the type, which will definitely introduce a bug into our system.!
operator after variable to tell the Typescript compiler that a variable isn't null.function square(x: number) {
return x * x;
}
const x : number | undefined;
const answer = square(x!);
string | undefined
. I have come across not-so-obvious bugs that were thrown in a completely different section of the code with a different error message because I allowed an undefined variable to be passed on. This happened because instead of handling the possibility of the environment variable being undefined, I decided non-null assertion was the way to go.any
and moving it to string. There are various ways of achieving this, which I have covered previously here, but I will take a look at a few notable ones.union
, unknown
, any
, etc. to a specific type:function doSomething(x: string | number) {
if(typeof x === "string") {
// do somethign with the string
} else {
// do something with the number
}
}
function doSomething(x?: string) {
if(x) {
// type of x is now string
}
}
function isRectangle(shape: unknown): shape is Rectangle {
if ("width" in shape && "height" in shape) {
// this is a rectangle
return true;
}
// it's not a rectangle
return false;
}
??
) or the or ( ||
) operator.// using the nullish coalescing operator
const API_URL = process.ENV.API_URL ?? "DEFAULT URL";
// using the OR (||) logical operator
const API_URL = process.ENV.API_URL || "DEFAULT URL";
let x : string | number;
// provide a default value if null or undefined
x ??= "Hello World"
// provide a default value if falsy
x ||= "Hello World"