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?

More than 5 years have passed since last update.

React.jsAdvent Calendar 2018

Day 22

TypeScript+Reactで、propsにデフォルト値を持たせたかった

Last updated at Posted at 2018-12-21

こう書きました

<SayHello {...createSayHelloProps({lastName: 'Iijima'})}/>

const SayHello: React.SFC<SayHelloProps> = props => {
  return (<div>Hello, {props.firstName} {props.lastName}</div>)
}

function createSayHelloProps({
  firstName = 'Kaga',
  lastName = 'Tetsuo'
}): SayHelloProps {
  return {
    firstName,
    lastName
  }
}

interface SayHelloProps {
  firstName: string
  lastName: string
}
  • 引数を hash にすることで、名前付き引数っぽく使っています
  • また、デフォルト値を持たせた関数を経由しているので、hash の key を省略可能です。

ちなみに、下記部分は hash のkey と value が同名の時の省略記法(tslint推奨)です。

return {
  firstName,
  lastName
}

// これと意味は同じ
return {
  firstName: firstName,
  lastName: lastName
}

おわりに

より良い書き方ありましたらコメントお願いします🙇‍♂️

1
0
2

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?