You can assert that a property exists, but then when you reference it on the next line, typescript is unable to infer from the control statement that myObj is not null.
I come across these issues all the time. I didn't realise this feature existed and I highly expect I'll need to use it at some point before the week is out.
I'm glad I showed you a new feature.
In your first case, you could create different types base on the response type, so you can detect the correct type if some field has or not has a specific value.
I leave you a simple case, I hope it can help you in the future.
type WsResponseOk = {
value: true
}
type WsResponseError = {
value: false;
error: string;
};
type WsResponse = WsResponseOk | WsResponseError;
const getResponse = (): WsResponse => ({ value: true })
let response = getResponse();
if (response.value) {
// response => WsResponseOk
response.value;
response.error; // Property 'error' does not exist on type 'WsResponseOk'.
} else {
// response => WsResponseError
response.value;
response.error;
}
Yes I do this but often the combinations are so complex it becomes impractical and often typescript is left unable to correctly infer which variation you're referring to. This is especially true when you're passing an object around several different functions or if you're using assertions that are out of your control that also don't offer sufficient type guarding.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Amazing.
There are many many times that you have 100% confidence in a property's existence, but typescript does not...
Off the top of my head: response data from an api where you know that if property a has a specific value, then property b will not be null.
Another example is if you're using something like jsx-control-statements in react:
You can assert that a property exists, but then when you reference it on the next line, typescript is unable to infer from the control statement that myObj is not null.
I come across these issues all the time. I didn't realise this feature existed and I highly expect I'll need to use it at some point before the week is out.
I'm glad I showed you a new feature.
In your first case, you could create different types base on the response type, so you can detect the correct type if some field has or not has a specific value.
I leave you a simple case, I hope it can help you in the future.
Yes I do this but often the combinations are so complex it becomes impractical and often typescript is left unable to correctly infer which variation you're referring to. This is especially true when you're passing an object around several different functions or if you're using assertions that are out of your control that also don't offer sufficient type guarding.