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 1 year has passed since last update.

TypeScriptの型をまとめてみた!

Posted at

この資料の続き

TS型

この記事ではTypeScriptの型を見ていきます。
実際に動かしてみてください。

boolean型、number型、string型

index.ts
let count: number = 100;
let float: number = 3.5;
let negative: number = -10;
let single = 'やあ';
let double = 'イエーい';
let back = `はーい`;
% tsc index.ts 

を実行してみると

index.js
var count = 100;
var float = 3.5;
var negative = -10;
var single = 'やあ';
var double = 'イエーい';
var back = "\u306F\u30FC\u3044";

型注釈と型推論

上のコードのnumberなどは型注釈ですが、型推論はTS側が型を推測してくれます。

index.ts
let hasValue = true;
let count = 100;
let float = 3.5;
let negative = -10;
let single = 'やあ';
let double = 'イエーい';
let back = `はーい`;

基本型推論を使った方がいいです。

index.ts
let message; //let message: any

anyはなんでも入るという型になります。
こういうのもあるので、一概に型推論がいいとは言えませんが

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

下の方法でできます。

index.ts
const player: {
    name:string;
    age:number;
    team:string;
} = {
    name: '大谷',
    age: 28,
    team: 'エンゼルス'
}

console.log(player);
console.log(player.name);
//% node index.js
//{ name: '大谷', age: 28, team: 'エンゼルス' }
//大谷
index.ts
const player: object = {
    name: '大谷',
    age: 28,
    team: 'エンゼルス'
}
console.log(player);
//% node index.js
//{ name: '大谷', age: 28, team: 'エンゼルス' }
//大谷

objectは無しでも書けます。

Array型

次は配列の型を見ます。

index.ts
const animal: string[] = ['Dog','Cat','Monkey','Lion']
animal.push('bird');
console.log(animal);

//% tsc index.ts 
//% node index.js
//[ 'Dog', 'Cat', 'Monkey', 'Lion', 'bird' ]
index.ts
const score: number[] = [90,80,50]
console.log(score[1]);
//% tsc index.ts 
//% node index.js
//80

Tuple型

内容が決まった配列を作る時に使います。
以下のように作ります。

const comic: [string,number,boolean] = ['ワンピース',500,false]
comic[0] = '鬼滅の刃';
console.log(comic);

//% tsc index.ts 
//% node index.js
//[ '鬼滅の刃', 500, false, 100 ]

列挙型

enumを使います。特定のまとまったグループのみを受け入れます。

今回はこちらの記事で確認お願いします。

any型

どんな型でも入ります。
anyはなるべく使わない方がいいみたいです。

Union型

複数の型を使います。

index.ts
let unionType: number | string = 1000;
unionType = 'こんにちは';
console.log(unionType);
//% tsc index.ts 
//% node index.js
//こんにちは

配列を使うとこんな感じです。

index.ts
let unionType: (number | string)[] = [100,'やあ'];
console.log(unionType);
//[ 100, 'やあ' ]

Literal型

特定の値のみを使います

この記事を参考にしてください。

Typeエイリアス

複雑な型でも変数みたいに使えます。

関数に型を適応

関数に型を適応させていきます。

index.ts
function add(score1: number,score2: number) {
    return score1 + score2
}

こんな感じに書いていきます。

function add(score1: number,score2: number): number {
    return score1 + score2
}

void型

関数の戻り値に使います。

index.ts
function sayGoodBye(): void{
    console.log('バイバイ');
}
console.log(sayGoodBye());

ここでは記載はないですが、undefine型やnull型もあります。

特定の関数のみを代入できる変数

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

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

callback関数の型

callback関数の場合を見ていきます。

inde.ts
function doubleHandle(num:number,callback:(num:number)=>void): void{
    const doubleNum = callback(num*2);
    console.log(doubleNum); 
}

doubleHandle(21,doubleNum => {
    return doubleNum
});

unknown型

anyと違い、型の制約があります。型安全性が保証されているany型です。

index.ts
let unknownInput: unknown;
let anyInput: any;
let text: string;
unknownInput = 'やあ';
unknownInput = 200;
unknownInput = true;
text = anyInput;
if(typeof unknownInput === 'string'){
    text = unknownInput;
}

unknownはなんでも入れることはできるが使用する時は上のif文みたいにして
保証する必要
があります。

never型を使う

起こり得ない値の型を使います

index.ts
function error(message:string){
    throw new Error(message);
}
console.log(error('This is an error'));

これは何も値は返ってきていない状態です。
ここでneverをつけることができます。

index.ts
function error(message:string): never{
    throw new Error(message);
}
console.log(error('This is an error'));

neverを消すと型推論はvoidになります。

index.ts
function error(message:string): void{
    throw new Error(message);
}
console.log(error('This is an error'));
index.js:64
    throw new Error(message);
    ^

Error: This is an error

みたいなエラーが出ます。

資料

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?