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

[Typescript] 基本的な型

0
Posted at

boolean

index.ts
let hasValue: boolean = true;
let hasValue: boolean = false;

number

index.ts
let count: number = 10;
let float: number = 3.14;
let negative: number = -3.14;

string

index.ts
let single: string = 'hello';
let double: string = "hello";
let back: string = `hello`;

型推論

index.ts
let hasValue = true;

:をはずしても↑はboolean型だと判断されます。
hoverしてみてもbooleanと出ますし、
↓のように代入してみてもエラーを返してくれます。

index.ts
hasValue = "thanks";

オブジェクトに型をつける

index.ts
const person: {
  name: string;
  age: number;
} = {
  name: "Jack",
  age: 20
}

ネストした場合も成り立つ

index.ts
const person = {
  name: {
    first: 'Jack',
    last: 'Smith'
  },
  age: 20
}

Array型

index.ts
const fruits = ['Apple', 'Banana', 'Grape']

型注釈の場合

index.ts
const fruits: string[ ] = ['Apple', 'Banana', 'Grape']

Tuple型

index.ts
const book: [string, number, boolean] = ['business', 1500, false];

↑は、[string, number, boolean]通りの値しか入りません。

ただし、それはあくまで初期値の場合の話で、後からpushすることはできます。
追加時にはエラーが出ない代わりに、出力時にエラーが出ます。
Image from Gyazo

Enum型

enumeration = 列挙
列挙型
特定のまとまったグループのみを使いたいときに使用します。

index.ts
enum CoffeeSize {
  SHORT = 'SHORT',
  TALL = 'TALL',
  GRANDE = 'GRANDE',
  VENTI = 'VENTI'
}

const coffee = {
  hot: true,
  size: CoffeeSize.GRANDE
}

any型

どんな型にもなる、なんでもありの型です。
なるべく使わないようにしましょう。

index.ts
let anything: any = true;
anything = 'hello';
anything = ['hello', 20, true];
anything = {};

let banana = 'banana';
banana = anything;
console.log(banana);

このように、カオスな状況になります。

Union型

複数の型を受け入れることができる型です。

↓は、numberもstringも受け入れることができます。

index.ts
let unionType: number | string = 10;
let unionTypes: (number | string)[] = [20, 'hello'];

2行目は配列です。

Literal型

特定の決まった値のみを扱う型です。

Typescriptはconstを使うとLiteral型になります。

↓は'apple'以外の値を取りません。

index.ts
const apple = 'apple';

型注釈で書くとこうなります。

index.ts
const apple: 'apple' = 'apple';

↓はUnion + Literalで3択のみ値を取ります。

index.ts
let clothSize: 'small' | 'medium' | 'large' =

type alias

型を変数のように扱うことができるものです。
alias = 別名

index.ts
type ClothSize = 'small' | 'medium' | 'large';
let clothSize: ClothSize = 'medium';

関数に型をつける

型をつける箇所は、パラメーターと戻り値です。

型注釈

index.ts
function add(num1: number, num2: number): number {
  return num1 + num2
}

add(3, 2);

パラメーターは値の後ろに付けて、戻り値は( )の後ろに付けます。

型推論

index.ts
function add(num1: number, num2: number) {
  return num1 + num2
}

add(3, 2);

戻り値には型推論が効きますが、パラメーターには効きません。
よって、パラメーターは必ず型注釈で型を書いてあげましょう。

何も書かない場合はany型になってしまいます。

また、戻り値も基本的に型注釈で書くようにしましょう。

void型

「何も返さない」という意味の型です。
関数が何も返さなかった場合、void型になります。

index.ts
function sayHello(): void {
  console.log('Hello!');
}

undefinedとnull

undefined型とnull型という型があります。

index.ts
let tmpNull: null = null;
let tmpUndefined: undefined = undefined;

関数を保持する変数に型を付ける

↓2つは結果が同じです。

index.ts
const anotherAdd = function add(num1: number, num2: number) {
  return num1 + num2
}
index.ts
const anotherAdd: (n1: number, n2: number) => number = function (num1, num2) {
  return num1 + num2
}

アロー関数
↓2つも結果が同じです。

index.ts
const doubleNumber = (number: number): number => number * 2;
index.ts
const doubleNumber: (num: number) => number = number => number * 2;

callback関数に型を付ける

index.ts
function doubleAndHandle(num: number, cb: (num: number) => number): void {
  const doubleNum = cb(num * 2);
  console.log(doubleNum);
}

doubleAndHandle(20, doubleNum => {
  return doubleNum
});

unknown型

anyより少し厳しい型です。

index.ts
let unknownInput: unknown;

unknownInput = 'hello';
unknownInput = 20;
unknownInput = true;

text = unknownInput;

↑のtextではエラーが発生します。
unknownInput = unknownと最初の行で定義されているからです。

しかし、↓はエラーが起きません。

index.ts
if(typeof unknownInput === 'string') {
  text = unknownInput;
}

Typescriptは頭が良いので
条件分岐後のこのunknownInputは、必ずstring型であると理解できるのです。

never型

決して何も返さない型です。
Errorや、エンドポイントがないものにはneverを付けることができます。

index.ts
function error(message: string): never {
  throw new Error(message);
}

console.log(error('This is error messages'));
index.ts
function error(message: string): never {
  throw new Error(message);
  while (true) {
    
  }
}
0
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
0
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?