Help us understand the problem. What is going on with this article?

TypeScriptの型と基本的な書き方

More than 3 years have passed since last update.

typescriptの型と宣言方法

型が存在していて、明示的にどの型を使うかを指定できる

String型

// 文字列以外を代入するとコンパイルエラーが発生
var s: string = 'str'

Number型

// 数値以外を代入するとコンパイルエラーが発生
var n: number = 123

Boolean型

// 真偽値以外を代入するとコンパイルエラーが発生
var b: boolean = true

Any型

// 従来のjavaScriptの変数型(コンパイルエラーにならない)
var a: any = 'any'

配列の宣言

// string型の配列
var fruits: string[] = ['apple', 'orange', 'grape'];

// number型の配列
var numbers: number[] = [1, 10, 100, 1000];

連想配列の宣言

// keyがstring型の連想配列
var hash1: { [key: string]: string; } = {};

// 値を格納
hash1['a'] = 'a'; 


// keyがnumber型の連想配列
var hash2: { [key: number]: string; } = {};

// 値を格納
hash2[1] = 'b'; 


// 型未指定の連想配列
var hash3: { [key]: string; } = {};

// 値を格納(string/numberどっちもいける)
hash3['a'] = 'c'; 
hash3[1] = 'd';

インタフェース宣言

interface HumanInterface{
    name: string,
    age: number,
    gender: string,
}

クラスの宣言

class Taro {    

    name: string
    age: number
    gender: string

}

// インターフェースをimplemtntsすることもできる
class Taro implements HumanInterface{

    name: string
    age: number
    gender: string

}

終わりに

ざっと書いてしまったので、クラスやインターフェースについては別記事で詳しくまとめたいと思います。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした