Answer the question
In order to leave comments, you need to log in
How to write a type guard for an individual interface field?
There is an interface that has a type field and the type of the attach field depends on the type field.
export interface PostAttach {
type: "video"|"audio",
attach: AttachVideo|AttachAudio
}
How can I write a type guard that would receive PostAttach as input and determine the type of the attach field? Like this:export function isAudio(attach: PostAttach): attach.attach is AttachAudio {
return attach.type === "audio";
}
Answer the question
In order to leave comments, you need to log in
interface PostAttachVideo {
type: 'video'
attach: AttachVideo
}
interface PostAttachAudio {
type: 'audio'
attach: AttachAudio
}
type PostAttach = PostAttachAudio | PostAttachVideo
function isAudio(attach: PostAttach): attach is PostAttachAudio {
return attach.type === 'audio';
}
In fact, there is no need for a separate function here. The usual if
is enough: Sandbox
A with your approach:
export interface PostAttach {
type: "video"|"audio",
attach: AttachVideo|AttachAudio
}
type
and attach
. For him, these are two unrelated fields. It assumes that any combination of "video"|"audio"
and is possible, AttachVideo|AttachAudio
and the fact that type = 'video'
it says nothing about the type of attach
. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question