Typescript 個人リファレンス

目次

Generics

// 基本
interface Box<T> {
	value: T;
}
const box01: Box<string> = { value: 'this is box' }


// 初期値を割り当てる
interface Box<T = string> {
	value: T;
}
const box02: Box = { value: 'this is box' }


// 型の制限をつける
interface Box<T extends string | number> {
	value: T;
}
const box03: Box<boolean> = { value: true } // error


// 関数型
// 関数実行時は型推論がされるので暗黙的に解決される
function boxValue<T>(arg: T) {
	return { value: arg }
}
const box03 = boxValue('test')
// 明示的に実行することもできる
const box04 = boxValue('test' as string | null)
const box04 = boxValue<string | null>('test')


// 関数を変数に代入する場合
const boxVal = <T>(arg: T) => { value: arg }