Why do you want to use the "non-null assertion operator"?
The status property can either be string | undefined.
What about passing an empty string or perhaps assigning a default value when you don't want to specify a value for status?
<Items status={status || ''}/>
Or:
type ItemProps = {
status?: string;
};
const Items: React.FC<ItemProps> = ({ status = 'statusDefaultValue' }) => <div>Some JSX</div>
It's a bit hard for me to understand your case without knowing the context. Hope this can help.
Answer from HereBeAndre on Stack OverflowWhy do you want to use the "non-null assertion operator"?
The status property can either be string | undefined.
What about passing an empty string or perhaps assigning a default value when you don't want to specify a value for status?
<Items status={status || ''}/>
Or:
type ItemProps = {
status?: string;
};
const Items: React.FC<ItemProps> = ({ status = 'statusDefaultValue' }) => <div>Some JSX</div>
It's a bit hard for me to understand your case without knowing the context. Hope this can help.
You can try to use the nullish coalescing operator (??) instead of a logical or (||), as it is a safer operator as some might prefer, like the following:
<Items status={status ?? ''}/>
It's called the "Non-null assertion operator" and it tells the compiler that x.getY() is not null.
It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says:
A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.
// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
// Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}
Edit
There's an issue for documenting this feature: Document non-null assertion operator (!)
Non-null assertion operator: !
- You tells the TS compiler that the value of a variable is not
null | undefined - Use it when you are in possession of knowledge that the TS compiler lacks.
Here is a trivial example of what it does:
let nullable1: null | number;
let nullable2: undefined | string;
let foo = nullable1! // type foo: number
let fooz = nullable2! // type fooz: string
It basically removes null | undefined from the type
When do I use this?
Typescript is already pretty good at inferring types for example using typeguards:
let nullable: null | number | undefined;
if (nullable) {
const foo = nullable; // ts can infer that foo: number, since if statements checks this
}
However sometimes we are in a scenario which looks like the following:
type Nullable = null | number | undefined;
let nullable: Nullable;
validate(nullable);
// Here we say to ts compiler:
// I, the programmer have checked this and foo is not null or undefined
const foo = nullable!; // foo: number
function validate(arg: Nullable) {
// normally usually more complex validation logic
// but now for an example
if (!arg) {
throw Error('validation failed')
}
}
My personal advice is to try to avoid this operator whenever possible. Let the compiler do the job of statically checking your code. However there are scenarios especially with vendor code where using this operator is unavoidable.
Been new to TS and having only tried it long ago, I'm confused about some things.
I have a simple html page where I'm getting 2 elements from it, a button and a div, so I did:
const BUTTON: HTMLButtonElement | null = document.querySelector("#get");
const DATA: HTMLDivElement | null = document.querySelector("#data");Everything looks good so far, even when I know those wont be null, they could be for whatever reson I guess.
Then I have a listener so when the button is clicked I change the content on the div.
BUTTON?.addEventListener("click", async () => {
DATA ? DATA.textContent = "WORLD" : "";
}); I understand the need of using ? after BUTTON (Seams reasonable) but the part I bet I'm doing wrong is that DATA ? line... Is that what I need to write to have TS not complain about my code?
DATA.textContent = "WORLD";
Object is possibly "null"
First my mind though... Ok you may be null so:
DATA?.textContent = "WORLD";
That gives me The left-hand side of an assignment expression may not be an optional property access.
Then I remember I saw somewhere the ! for those cases.
DATA!.textContent = "WORLD";
And while I believe that's the "solution" I get a warning from eslint this time Forbidden non-null assertion.
Even then if DATA is null, code will throw an error, while my first piece of code wont.
What's the way to go here?
Please add '@typescript-eslint/no-non-null-assertion': 'off' to your config file like below.
module.exports = {
...
rules: {
...
'@typescript-eslint/no-non-null-assertion': 'off'
},
...
}
If you're attempting to disable a rule on the entire file, adding this comment in the file top to ignore will work:
/* eslint-disable @typescript-eslint/no-non-null-assertion */
If you're attempting to disable a rule on the next line only (rather than for an entire file), adding this comment directly above the line to ignore will work:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion