Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make typescript know my variable is not undefined anymore

Tags:

typescript

Here is my case:

I am using a Remix loader which get params from the URL but the params are defined as string | undefined

If the variable is undefined I would like to throw a redirection

export const loader: LoaderFunction = async ({ params }) => {
  const { myVar } = params; // myVar: string | undefined 
  definedOrRedirect(myVar, "/"); // Checks if undefined
  return fetchSomething(myVar); // myVar: string | undefined
};

Is there a way to make typescript know that if it didn't throw myVar is not undefined?

like image 391
Jason Van Malder Avatar asked Dec 20 '21 19:12

Jason Van Malder


People also ask

How do you avoid undefined values in TypeScript?

To avoid undefined values when using or accessing the optional object properties, the basic idea is to check the property value using an if conditional statement or the optional chaining operator before accessing the object property in TypeScript.

Why is my variable undefined TypeScript?

Whenever a variable is declared without assigning any value to it in TypeScript, then the variable is called undefined, so the variables that are declared without initializing a value to it are initialized as undefined, and this undefined can be assigned to variables of any data type, but undefined variables are not so ...

How do you change from undefined to string in TypeScript?

The typescript compiler performs strict null checks, which means you can't pass a string | undefined variable into a method that expects a string . To fix this you have to perform an explicit check for undefined before calling luminaireReplaceLuminaire() .

What does ?: Mean in TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

How to make a variable null or undefined in typescript?

To make a variable null we must assign null value to it as by default in typescript unassigned values are termed undefined. We can use typeof or ‘==’ or ‘===’ to check if a variable is null or undefined in typescript. By using typescript compiler tcs we transpile typescript code to javascript and then run the javascript file.

How does typescript know if a variable is a string?

The Name type can be null, undefined or a string. In the if statement, we check if the variable is not null and is not undefined. If both conditions are met, TypeScript knows that the variable is a string and allows us to use string-specific methods like toLowerCase ().

How to check for an undefined variable in JavaScript?

In Typescript 2 you can use Undefined type to check for undefined values. So if you declare a variable as: if (uemail) { console.log ("I have something"); } else { console.log ("Nothing here..."); } Go and check out the answer from here: Is there a standard function to check for null, undefined, or blank variables in JavaScript?

How to tell if x is defined or not in typescript?

TypeScript can tell that x is definitely not defined, because it is a block-scoped variable and you can see the whole block. If you know better than the compiler, you can separate the lines: const def_val = 'default'; let x: string; x = (typeof x === 'undefined') ? def_val : x;


Video Answer


1 Answers

You can make throwIfUndefined an assertion function to narrow the type of its argument to something that does not include undefined in its domain. An assertion function has an assertion type predicate of the form asserts x is Y as its return type, where x is the name of one of the function's parameters, and Y is the subtype of typeof X that we narrow x to assuming the function returns successfully. Assertion functions cannot return a defined value; they are basically void-returning functions.

For throwIfUndefined, here's the normal way to do it, as a function statement:

function throwIfUndefined<T>(x: T | undefined): asserts x is T {
    if (typeof x === "undefined") throw new Error("OH NOEZ");
}

You can also write it as an arrow function, although you need to explicitly annotate the variable with its type for the control flow analysis to happen correctly:

const throwIfUndefined: <T, >(x: T | undefined) => asserts x is T = x => {
    if (typeof x === "undefined") throw new Error("OH NOEZ");
}

Either way should work:

const Index = ({ params }: { params: { myVar: string | undefined } }) => {
    const { myVar } = params // myVar: string | undefined
    // myVar.toUpperCase // <-- error, Object is possibly 'undefined'
    throwIfUndefined(myVar);
    return myVar.toUpperCase() // no error now
}

try {
    console.log(Index({
        params: {
            myVar: Math.random() < 0.5 ? "hello" : undefined
        }
    })) // 50% "HELLO" 
} catch (e) {
    console.log(e); // 50% "OH NOEZ"
}

Playground link to code

like image 131
jcalz Avatar answered Nov 15 '22 09:11

jcalz