LoginSignup
2
2

More than 5 years have passed since last update.

【備忘録】『速習TYPESCRIPT』の参考になった部分まとめ

Last updated at Posted at 2018-10-10

何かあればご指摘大歓迎です:joy:

オブジェクトの作り方

let obj: { [index: string]: string; } = {
    'hoge': 'ほげ',
    'foo': 'ふー'
}

console.log(obj.hoge);
console.log(obj['hoge'])

interfaceを使ってもよい

interface StringMap {
    [index: string]: string;
}

let obj: StringMap  = {
    'hoge': 'ほげ',
    'foo': 'ふー'
}

アロー関数を使ったthis固定の簡素なコード

let triangle = (base: number, height: number): number => base * height / 2;

引数が省略できる関数は ? をつける

swiftのoptionalのような?


 function showTime(time?: Date): string {
    // ...
}

デフォルト値がありの引数は引数リストの末尾に書く

不特定多数の引数の表現

これは arguments のようなArrayライクではなく真性のArray

function sum(...values: number[]) {
    let result = 0;
    for (let value of values) {
        result += value;
    }
    return result;
}

console.log(sum(1, 5, -8, 10));

関数のオーバーロード

ちょっと癖がある

function show(value: number) void;
function show(value: boolean) void;
function show(value: any): void {
    if (typeof value === 'number') {
        console.log(value.toFixed(0));
    } else {
        console.log(value ? '' : '');
    }
}

show(10.358);
show(false);
show('hoge');

typeofはプリミティブ型の判定しかできない。クラス型ならinstanceof。

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