You can use the null assertion operator ! to tell the ts editor/compiler that you guarantee that the object has value at runtime. This is one way to suppress the error message.
In the example below, there’s an error when process function is called. This is because the function expects a string type of value. However, we’re using the optional chaining operator ?, indicating that the value might be undefined. This does not match the function signature.
You can change the function signature to id: string | undefined or surround the function call with an if condition to check if the value is undefined.
If you are sure that the value will not be undefined at any point (for example, there’s already a validation or initialization before the current context), you can use the null assertion operator in this way:
this.process(data!.id)
type data = {
id: string
}
let data: data;
this.process(data?.id) // Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.
process(id: string) {
console.log(id)
}