B
B
Bone2020-11-20 11:03:01
typescript
Bone, 2020-11-20 11:03:01

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

2 answer(s)
L
Lynn "Coffee Man", 2020-11-20
@Bone

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';
}

sandbox

A
Alex, 2020-11-20
@Kozack

In fact, there is no need for a separate function here. The usual ifis enough: Sandbox
A with your approach:

export interface PostAttach {
    type: "video"|"audio",
    attach: AttachVideo|AttachAudio
}

TS will not see the connection between the fields typeand attach. For him, these are two unrelated fields. It assumes that any combination of "video"|"audio"and is possible, AttachVideo|AttachAudioand the fact that type = 'video'it says nothing about the type of attach.
Therefore, they need to be divided from one universal interface into several special cases.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question