admin管理员组文章数量:1289633
I have a type Response
type MainTypeResponse = {
message: 'OK' | 'ERROR';
error?: string;
}
If message = 'ERROR', then error
field is present.
Problem, when response is success (message = 'OK'). Error property does not present, and another properties is.
type SomeAnotherResponse = MainTypeResponse & {
prop1: 'string';
prop2: ''number;
}
I tried to union types (error)
type SomeAnotherResponse = MainTypeResponse | {
message: MainTypeResponse['message']
prop1: 'string';
prop2: ''number;
}
I don't want to condition it
prop1?: string
In code, i want to check it with this construction
const result: SomeAnotherResponse = '...'
if (result.message === 'OK') {
// ts error
console.log(result.prop1);
}
So, something like
type SomeAnotherResponse<T> = T extends {message: 'OK'} ? {} : {}
I have a type Response
type MainTypeResponse = {
message: 'OK' | 'ERROR';
error?: string;
}
If message = 'ERROR', then error
field is present.
Problem, when response is success (message = 'OK'). Error property does not present, and another properties is.
type SomeAnotherResponse = MainTypeResponse & {
prop1: 'string';
prop2: ''number;
}
I tried to union types (error)
type SomeAnotherResponse = MainTypeResponse | {
message: MainTypeResponse['message']
prop1: 'string';
prop2: ''number;
}
I don't want to condition it
prop1?: string
In code, i want to check it with this construction
const result: SomeAnotherResponse = '...'
if (result.message === 'OK') {
// ts error
console.log(result.prop1);
}
So, something like
type SomeAnotherResponse<T> = T extends {message: 'OK'} ? {} : {}
Share
Improve this question
asked Feb 21 at 9:45
DmoDmo
251 silver badge5 bronze badges
1 Answer
Reset to default 2The simplest approach is to just define two separate types, and then create a union of those types. TypeScript will correctly narrow the type based on the value of the discriminator property:
type SuccessResponse = {
message: 'OK';
prop1: string;
prop2: number;
};
type ErrorResponse = {
message: 'ERROR';
error: string;
}
type MainResponse = SuccessResponse | ErrorResponse;
function handleResponse(response: MainResponse) {
if (response.message === 'OK') {
console.log(response.prop1); // OK
console.log(response.error); // Error
}
}
Playground link
The handbook refers to this as a discriminated union.
本文标签: Typescript check object property by existence of another propertyStack Overflow
版权声明:本文标题:Typescript check object property by existence of another property - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741393850a2376259.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论