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
I've been working on a React TS project creating a Connect Four game, and I've been struggling a lot with TS errors regarding an array state. For reference, here's what the "board" state looks like:
const [board, setBoard] = useState<number[][]>([
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
]);No issues for the most part, but when I try to update the array like so (marking line numbers):
1 const play = useCallback(
2 (col: number) => {
3 if (board[col][5] === 0 && !gameOver.winner) {
4 setBoard((prev) => {
5 const current = [...prev];
6 for (let row = 0; row < current[col].length; row++) {
7 if (current[col][row] === 0) {
8 current[col][row] = isPlayer1Turn ? 1 : 2;
9 break;
10 }
11 }
12 return [...current];
13 });
14 setIsPlayer1Turn((prev) => !prev);
15 setTimer(30);
16 }
17 },
18 [board, gameOver.winner, isPlayer1Turn]
19 );At lines 3, 6, 7, and 8, the IDE is complaining about board[col] and current[col] being possiby undefined:
Object is possibly 'undefined'.
I'm struggling hard finding relevant search results, to be honest. Why is board[col], and subesquently, current[col] possibly undefined? Is it because it assumes that col may be larger than the board length? I did try wrapping the code inside an if statement to check that (knowing fully well that it never is) but that didn't seem to fix the issue.
I did finish the project with no issues but these errors are still bothering me and I really need to learn more about them. I really appreciate all the help so thanks a lot in advance!
Typescript does not check defaultProps for function components. If you want a default value, you should use ES6 default values, as in:
type Props = {
name?: string
age: number
}
const Test: FC<Props> = ({ name = "John" }) => {
}
What you could do is:
{props.name ? props.name : "Jhon"}
Hello guys, i need your help, i would like to know which you think is a better approach:
1 --------------------------------------------
const {content} = props;
if(content !== "undefined"){
//code
}
2 --------------------------------------------
const {content = null} = props;
if(!content){
//code
}
Hi there. I'm using zustand for state management within my React app and am battling with a problem. One of the main stores driving the app, called 'session config store', is used to contain data that is retrieved from a network request and is vital to how the session behaves. We have a component that is responsible for triggering this network request and then saving the data to the store. This component is rendered immediately. Therefore, the store will be populated for the rest of the user journey.
Because the data isn't immediately available, we have to initialise the store with undefined values. So our store's types might look like this:
type SessionConfigData = {
sessionId?: string;
sessionToken?: string;
}
const useSessionConfigStore = () => createStore<SessionConfigData>({
sessionId: undefined,
sessionToken: undefined,
})What's annoying about this is that we know that these properties won't be undefined in any of the other components. So we have a couple of options:
add a bunch of type checks and throw an error if the value is undefined
use the non-nullish assertion operator to ignore these "might be, but in practical terms won't be" undefined values, essentially disabling TypeScript
Example of what I mean:
// This sucks
const someFunction = (sessionId: string | undefined) => {
if(!sessionId) {
throw new Error('No sessionId even though there definitely will be. I just want to make TS happy :(');
}
doSomethingElse(sessionId);
}
// This sucks too
someFunction(sessionId!);This is a simplified example. Of course with the above, we could simply provide empty strings. This isn't viable with the real data.
We can solve the problem by keeping the store inside React context, meaning that it can be created when a component is mounted (and the data is ready). However, this would add a lot of complexity to the codebase. Doing this seems a bit ridiculous for only trying to keep TypeScript happy. Does anyone have any ideas for a better solution? This must surely be a common enough problem...
Update: For simplicity, I replicated the original error with simpler code.
Update 2: I got around this by using a type guard for T. Thank u/ritajalilip for the suggestion. I still think Typescript should handle this better though.
As you can see on the screenshot, inside the if statement I'm asserting that x is not undefined. However Typescript is failing to acknowledge and still thinks that x can be undefined.
Any idea of what's going on?