disclaimer: this is dangerous stuff, typescript is pretty good at infering things and you should probably trust that over these funky things
You can force typescript to identify a new variable or a resulting variable to be of a specific type
Add a magic "as" asertion and our result is now:
more info: https://basarat.gitbook.io/typescript/type-system/type-assertion
Sometimes you would only run a function or render a component if you thought that a specific item in your context is defined. Or you want Typescript to assume that a variable is not null or undefined.
normally you would do:
getNameFromTask = () => {
const { task } = this.context; // task is ITask or undefined
if (!task) return new Error('this should not have happened!')
return task.name
}
with the non-null assertion operator you can do this instead:
getNameFromTask = () => {
const { task } = this.context; // Task is ITask or undefined;
return task!.name
}
The bang here tells typescript that you are 100% sure that the variable will be present.
Modern ECMAScript as well as Typescript also support the "safe operator" which is sort of a reverse on the !.
so if you have the last example:
you could instead write that as:
?. will only execute the function or read the variable after it when the variable is not
null
orundefined
.this does not protect from mismatching types though! so
task?.functionThatDoesntExists()
will throw an error if task is defined.more info: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining