1
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?

TypeScriptでプロパティに関数を持つオブジェクト型を宣言する方法

Last updated at Posted at 2025-04-27

以下のように書く

type Myfunc = {
  (str?: string) : void
  (num?: number): void
}

const myFunc: Myfunc = (num) => {
  console.log(num)
}
const myStrFunc: Myfunc = (str) => {
  console.log(str)
}

myFunc(100)
myStrFunc('hoge')

このように書くと、関数ではなくプリミティブ型になる
string型を渡すとエラーになる

type Myfunc = {
  str?: string // このように定義すると、関数ではなくプリミティブ型になる
  (num?: number): void
}

// strを渡しているが、関数に対して型を当てているので、numを引数に持つ関数の方を型として設定してしまう
const myStrFunc: Myfunc = (str) => {
  console.log(str)
}

myStrFunc('hoge') // TS2345: Argument of type string is not assignable to parameter of type number

エディターで関数がどのように定義されているか都度確認するとすぐ気づける & TypeScriptがどういう風に型を解釈するしようとするか考えるのが大事だと思った
スクリーンショット 2025-04-27 12.47.40.png

1
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
1
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?