LoginSignup
0
1

More than 3 years have passed since last update.

typescriptでnumberが自然数かどうか、booleanで返す関数

Last updated at Posted at 2020-12-23

typescriptで自然数を判別したい

調べると、型でなんとかしようとする記事が目立った。
でもなんかむずそうだから、普通に関数でやろうと思った。

// 自然数だったらtrueを返す
const isNatureNum = (num: number): boolean => num > 0 && isInteger(num);

使い所

cssのプロパティって、自然数しか使えない場面ってある。
自分の場合、grid使うときにrowを制限したいときとか使った。
この実装だとlimitRownull , undefined , 0 , '' らへんは全部grid-auto-rowsになるはず(間違ってたらごめんね)
そもそも型でnumberに絞ってるけどね。

isNatureNum(prop.limitRow)
    ? {
        overflow: 'hidden',
        gridTemplateRows: `${prop.gridHeight}`,
        height: 'auto',
        maxHeight: `calc(${prop.gridHeight} * ${prop.limitRow})`,
      }
    : { gridAutoRows: `${prop.gridHeight}` };

もっといい方法あったら教えてください

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