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.
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.