TypeScript #4 特殊な型(void/undefined/null/never)
void型
void型とは、何も値を取らないときに使う型となります。変数なのに値がない?ってなんのこと??
Voidとは変数ではなく関数が値(戻り値:return)を返さない関数を定義するときに使います。
C言語を経験されている方は馴染みがあると思います。例えば、標準出力をするだけの関数などの処理結果をとってもあまり有用ではないときは、その関数は戻り値不要として定義します。
ただ、下記例を実行するとわかるのですが、実際は、下記例での実行結果は「Undefined」が帰ってきています。あれ?値を返さないのでは??と思いますが、Typescriptではvoidが取れる値はnullとUndefinedのみ取ることができます。これらは次に説明します。
// void型で関数を作成する
function voidTest: void{
console.log("Called voidTest!!");
}
console.log(voidTest());

nullとundefined
TypeScriptでは値がない( null) 定義がない( undefined) のそれぞれの型が用意されています。null と undefined は全ての型のサブタイプとなっているため、例えば number 型の変数に null をセットすることができます。そのため、nullは様々な変数型の初期化の際にnullを入れることができるようになります。
基本的に、型としてこれらのみで使用することはないと思います。いずれかの変数の初期値などにnullやundefinedを使うケースが多いと思います。
//undefined,nullを定義してみる(あまり使わないけど)
let undefinedTypes: undefined = undefined;
let Nothing: null = null;
//undefined,nullは他の型のサブタイプなので代入可能
let StringTypes: string = undefined;
let NumberValue: number = null;

never
Never型は 決して発生しない値 です。基本的には呼び出すと必ず例外が発生するような関数の戻り値などに利用します。
// 例外が発生する関数 returnされない
function error(message: string): never{
throw new Error(message);
}
try{
let result = error('エラーテスト');
console.log(result);
} catch(error) {
console.log(error);
}
// never型は値を代入できない(nullやUndefinedも入らない)
// let bar: never = undefined;
// ただし、never型 にはerrorは入る
let bar2: never = error('err');
ディスカッション
コメント一覧
Hey there would you mind letting me know which hosting company you’re using?
I’ve loaded your blog in 3 different browsers and I must say this blog loads a lot faster then most.
Can you recommend a good hosting provider at a honest price?
Kudos, I appreciate it!
Undeniably believe that which you stated. Your favorite justification appeared to be
on the net the simplest thing to be aware of. I say to you,
I definitely get irked while people consider worries that
they plainly don’t know about. You managed to hit the nail
upon the top and defined out the whole thing without
having side-effects , people can take a signal. Will probably
be back to get more. Thanks