1
2

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

[TypeScript] チートシート

Posted at
インストール
//npmでインストール
npm install TypeScript
//yarnでインストール
yarn add global typescript
//sample.ts ファイルを実行 (実行後にコンパイルされたjsファイルが生成される)
npx tsc sample.ts
any

any型にはどんな型でも代入できます。

let hoge: any;
hoge = '文字'
hoge = 123
void

voidは関数に戻り値がないときに使います。

function log(message): void {
    console.log(message);
}
null / undefined

値がnullで現在利用できないことを意味します。
undefinedは初期化されていないことを意味します。

function hoge(props: string | null | undefined) {}
never

bottom形(値を持たない型)の一つ。
どんな変数も入れることが出来ないです。
逆にどんな型にも入れることができます。


function error(message: string): never {
    throw new Error(message);
}
真偽値 - boolean

true or falseの真偽値を扱います。

let bool: boolean;
bool = true;
bool = false;
数値 - number

数値は浮動小数値(2,8,10,16進数のリテラル)を扱います。

function add (a: number, b: number): number {
  return a + b
}
文字列 - string

文字列を扱います。

let str: string;
str = '文字を代入';
str = 1; // Error
配列 - type[ ], Array

配列の中身を型定義できます。

let arr: string[];
//この方法でも良い ↓
//let arr: Array<string>;
arr[0] = "hogehoge";  
arr[1] = 1; //Error  
タプル - [string, number]

配列を表し、長さが2の配列で、0番目に文字列が、1番目に数値を表しています。

const foo: [string, number] = ['foo', 5];

const str: string = foo[0];
合併型 - union

union型は値が複数の型のどれかに当てはまるような型を表しています。

let value: string | number = 'foo';
value = 100;
value = '文字';
value = true; // Error
enum

定数をひとまとめに定義できます。

enum Card {
  Clubs = "clubs",
  Diamonds = "diamonds",
  Hearts = "hearts",
  Spades = "spades",
}
console.log(Card.Diamonds); // = diamonds

型の定義方法

let flg: boolean
let flg: boolean = false

function add (a: number, b: number): number {
  return a + b
}

型アサーション

let len: number = (input as string).length
function object(this: {a: number, b: number}, a: number, b: number) {
  this.a = a;
  this.b = b;
  return this;
}

let a = object(1,2);

互換性のある型である場合、<型名>のような形で、変数やリテラル前付与することで、
型を明示的に変換してくれます。

オブジェクト型

//{foo: string; bar: number}という型は、fooというプロパティがstring型の値を持ち
//barというプロパティがnumber型の値を持つようなオブジェクトの型
interface MyObj {
  foo: string;
  bar: number;
}

const a: MyObj = {
  foo: 'foo',
  bar: 3,
};

関数インターフェース

interface SomeFunc{
    (a: string, b: string): boolean
}

const someFunc: SomeFunc = (a, b, c) => {   // error(c)
    return 'bad return'                     // error
}

関数のシグネチャを宣言。

クラスインターフェース

//クラスの構造を定義
interface MyInterface{
    getName():void;
    getDetail():{address:string};
}

class MyClass implements MyInterface{
    private getName(){
    }
    public getDetail(){
        return {
                address:'TOKYO'
        }
    }
}

クラスの構造を定義。
プロパティのアクセス範囲を指定。

オプション引数(?)

function required(some: string){
    return some
}

function optional(some?: string){
    return some
}

?でオプションにできます。

ジェネリック型

//関数の場合
function echo<T>(param: T): T{
    return param
}

echo('hoge')
echo(123)

//クラスの場合
class SomeClass<T>{
    someParam: T
    someMethod(param: T): T{
        // ...
    }
}

const strInstance = new SomeClass<string>()
const numInstance = new SomeClass<number>()

<>で囲った名前の列を与えることで、型の定義の中でそれらの名前を型変数として
使うことができます。

タプル型と可変長引数

type Args = [string, number, boolean];

const func = (...args: Args) => args[1];

const hoge = func('foo', 3, true);
// hogeはnumber型になる

タプル型を関数の可変長引数の型を表す。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?