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?

【 TypeScript 】基礎

0
Posted at

1. TypeScript 基礎的な型

プリミティブ型

boolean:真偽値
number:数値
string:文字列
bigunt:大きな整数
symbol:一意な値を示す
undefined:値が定義されていない状態を示す
null:値が存在しない状態を示す

const isReady: boolean = false;
const age: number = 25;
const fullName: string = "John Doe";
const bigNumber: bigint = 100n;
const uniqueSymbol: symbol = Symbol("unique");
const notDefined: undefined = undefined;
const empty: null = null;

bigint symbolについて

bigunt
number型では扱えない非常に大きな整数を正確に表現するために使う
数字の最後にnを書く(例:const a = 1234567890n

symbol
boolean型やnumber型は値が同じであれば、等価比較がtrueになる。一方、シンボルはシンボル名が同じでも、初期化した場所が違うとfalseになる。

const s1 = Symbol("foo");
const s2 = Symbol("foo");
console.log(s1 === s1); // → true
console.log(s1 === s2); // → false

特殊な型

any:なんでも代入できる型。操作に制限がなく、自由度は高いが、型の安全性が弱まる。
unknownany型と似て、何でも代入できる型。その値に対する操作は制限され、型の安全性が保たれる。
void:値が存在しないことを示す。関数が何も返さない場合に使用する。
never:決して何も返さないことを示す。エラーを投げる関数や無限ループの関数の戻り値として使用する。

const a: any = 100; // 代入できる
console.log(a * 3); // 操作もできる
 
const x: unknown = 100; // 代入はできる
console.log(x * 3); // 操作はできない
 
// 戻り値のない関数
function doSomething(): void {}
 
// 戻り値を返すことがありえない関数
function throwError(): never {
  throw new Error();
}

型エイリアスとインターフェース

Mapped Types

オブジェクトのフィールド名をあえて指定せず、プロパティのみを指定したい場合にインデックス型が使え、後から任意の型変数名にできる。

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?