3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypeScript 4.9時代の型ガードの書き方

Posted at

コード

interface B {
    b: string
}
interface A {
    a: B
}

const isB = (arg: unknown): arg is B => {
    return typeof arg === 'object' && arg != null && 'b' in arg && typeof arg.b === 'string'
}

const isA = (arg?: unknown): arg is A => {
    return typeof arg === 'object' && arg != null && 'a' in arg && isB(arg.a)
}

説明

TypeScirpt4.9からif ('a' in arg)と書くことによって、if文内ではargRecord<'a', unknown>と扱われる機能が追加されました。この機能により、これまで実質的に不可能だった型ガード関数の引数をunknown型にすることが可能となりました。ただし、この機能を使用するためにはargobjectに絞り込まれている必要があり、そのためtypeof arg === 'object'arg != nullが必要になります。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?