2
0

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 5 years have passed since last update.

TypeScript で引数の文字列に応じて戻り値の型が違う関数の書き方

Posted at

TypeScript でどう書くの?と聞かれたので、書いてみた。

type NameType = 'name'
type AgeType = 'age'

function query(t: NameType): string
function query(t: AgeType): number

function query(t: NameType | AgeType): any {
    if (t === 'name') {
        return 'わたしです'
    } else if (t === 'age') {
        return 24
    }
}

let name = query('name') // name is string
let age = query('age') // age is number

基本的な方針は Handbook > Functions > Overloads に従って、型判定のところを単純に文字列と比較しています。

NameType | AgeType | AddressType | ... ……のように増えてきたら type AllTypes = NameType | AgeType | AddressType | ... のようにして function query(t: AllTypes) のようにするとよいでしょう。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?