In TypeScript 2, you can use the undefined type to check for undefined values.
If you declare a variable as:
let uemail : string | undefined;
Then you can check if the variable uemail is undefined like this:
if(uemail === undefined)
{
}
Answer from ashish on Stack OverflowIn TypeScript 2, you can use the undefined type to check for undefined values.
If you declare a variable as:
let uemail : string | undefined;
Then you can check if the variable uemail is undefined like this:
if(uemail === undefined)
{
}
From Typescript 3.7 on, you can also use nullish coalescing:
let x = foo ?? bar();
Which is the equivalent for checking for null or undefined:
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
While not exactly the same, you could write your code as:
var uemail = localStorage.getItem("useremail") ?? alert('Undefined');
Videos
What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like
componentWillReceiveProps(nextProps) {
if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
console.log("new title is", nextProps.blog.title);
console.log("new body content is", nextProps.blog.content["body"]);
this.setState({
title: nextProps.blog.title,
body: nextProps.blog.content["body"]
})
}
}
You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value
In order to check for undefined, you can also use the typeof operator like
typeof nextProps.blog.content != "undefined"
I was face same problem ..... And I got solution by using typeof()
if (typeof(value) !== 'undefined' && value != null) {
console.log('Not Undefined and Not Null')
} else {
console.log('Undefined or Null')
}
You must have to use typeof() to identified undefined
This code do not work at all, but not sure why.
type IsUndefined<T> = T extends undefined ? 1 : 0;
For example:
type IsTypeUndefined = IsUndefined<number | undefined>; // This returns: 1 | 0
Is there a way for check if a type is undefined in a conditional?
Hello. I have a simple question, most likely some rookie mistake I am making, but not exactly sure why it's happening.
I have a simple interface IPerson, a person object, and finally a function searchPerson that lets you search a person's hobbies if they have any.
TypeScript Playground link
interface IPerson {
skills?: {
name: string;
}[];
hobbies?: {
name: string;
}[];
}
const person: IPerson = {
hobbies: [
{ name: 'programming' },
{ name: 'gaming' },
]
};
const searchPerson = ({ type, search }: { type: keyof IPerson, search: string }) => {
if (type === 'hobbies') {
if (person[type]) {
person[type].find(hobby => hobby.name === search); // <= error is here
}
}
};
All seems to work as intended, except for the fact that Typescript is complaining that Object is possibly 'undefined'. at the end of my function at the person[type].find(...) part, even though just the line above I am checking if if (person[type) is not undefined.
In the past I have dealt with something similar. For example, instead of keyof IPerson as type parameter of the function, I was using an arbitrary string which was causing issues, but here I am clearly telling TypeScript that type should be a key of IPerson, and since hobbies is an optional parameter I am checking if (person[type]) exists first. Yet it's still telling me that it's possibly undefined.
I am kinda confused, anyone has an idea what is happening here or can point me in the right direction? Cheers!
EDIT: Forgot to mention, I am aware that I can use optional chaining (person[type]?.find(...)) or non-null assertion operator (person[type]!.find(...)) but I am trying to understand why this is treated as undefined, rather than looking for a workaround.
Try first assigning person[type] to a variable, then do the condition and the find on that variable. That should work. I remember reading a while back that typescript does this for safety because it cannot statically determine the difference between a getter and a property so what is truthy on one line may no longer be on the next if it's a getter.
It’s possible to construct an object that implements the IPerson interface but returns a different value each time you access person[“hobbies”]. So, the compiler doesn’t know that the first result of person[type] being defined means the second result will be as well.
Therefore, you need to access it once and store it, then write your type guard against the stored value:
const hobbies = person[type]
if (hobbies) {
hobbies.find(…)
}
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
You could skip definedOrRedirect and use an explicit check:
export const loader: LoaderFunction = async ({ params }) => {
const { myVar } = params; // myVar: string | undefined
if (myVar == undefined) {
return redirect("/");
}
return fetchSomething(myVar); // myVar: string
}
Or you could keep definedOrRedirect and declare it with an assertion as jcalz suggests:
function definedOrRedirect(variable, path): asserts variable is string
{
if (variable == undefined) {
return redirect(path);
}
}
export const loader: LoaderFunction = async ({ params }) => {
const { myVar } = params; // myVar: string | undefined
definedOrRedirect(myVar, "/");
return fetchSomething(myVar); // myVar: string
}