[TypeScript]基本の型
- #Tech
- #TypeScript
この記事でやらないこと
- TypeScript とはのような概念理解
- 実践的な TypeScript の使い方
こちらに関しては他のブログでたくさん紹介されているので、今回は省かせていただきます。
TypeScript の型(基本)
プリミティブ型
TypeScript 以下の型 7 つをプリミティブ型と呼びます。
文字列型(string)
文字列のみを受け取る型
const foo: string = "Hello, TypeScript!";
const foo: string = 111; // error数値型(number)
数字のみを受け取る型
const foo: number = 0;
const foo: number = "Hello, TypeScript!"; // error論理型(boolean)
真偽値(true/false)のみを受け取る型
const foo: boolean = true;
const foo: boolean = false;
const foo: boolean = "Hello, TypeScript!"; // errorundefined 型
undefined のみを受け取る型
const foo: undefined = undefined;
const foo: undefined = null; // errornull 型
null のみを受け取る型
const foo: null = null;
const foo: null = undefined; // errorsymbol 型と bigint 型
後は他にも symbol 型と bigint 型がありますが、あまり見たことがなく、参考にした記事でもそこまで深く書かれていなかったので、今回は割愛させていただきます。
オブジェクト型
TypeScript では、プリミティブ型以外の型をオブジェクト型と呼びます。
any 型
なんでも代入できてしまう型。
any型の値はどんな型とも相互変換可能であり、実質TypeScriptの型システムを無視することに相当します。(つまりTypeScriptの意味がなくなってしまう)
let foo: any = "hello world!!";
foo = 111;
foo = true;ですが、僕自身がまだまだ型付けができないので、anyを使うこともしばしばあります。
JavaScript → TypeScriptに置き換える際は難しいので、anyから初めて、段階的に型付けをしていくこともあるみたいです。
void 型
この型は主に関数の返り値の型として使われ、「何も返さない」ことを表します。
const foo = (): void => {
alert("hello");
};ちなみに、「何も返さない」とは、「returnしない」 / 「返り値がない」と言うことなので、
const foo = (): void => {
alert("hello");
return;
}
const foo = (): void => {
alert("hello");
return undefind
}と同じ意味になります。
配列型
配列型には二種類の書き方があります。
const foo: string[] = ["aaa", "bbb"];
const foo: Array<string> = ["aaa", "bbb"];二番目のArray<string>という書き方は、TypeScriptのジェネリクスという機能を使っています。
ちなみに一番目の書き方の方が、よく使われる...らしい...
オブジェクト
オブジェクト型では、{foo: string; bar: number}のような形で、型定義をします。
const obj: { foo: string, bar: number } = {
foo: 'aaa',
bar: 111
}{foo: string; bar: number}以外を代入しようとすると、エラーになります。
const obj: { foo: string, bar: number } = {
foo: 'aaa',
bar: 111,
baz: true // error
}オブジェクト型は、実際に開発する際にはコードが長くなりがちなので、よくtypeやinterfaceを用いられることが多い印象です。typeとinterfaceの違いについては今回は割愛させていただいて、typeを用いて、例を書いてみます。
type Props = {
name: string,
age: number,
country: string,
}
const obj: Props = {
name: "Yuto",
age: 20,
country: "Japan"
}個人的には、typeの方がinterfaceよりも使われている印象です。
まとめ
今回の内容は以上です。
引き続き、勉強していって、ある程度学んだらまた記事にしてアウトプットしていこうと思います。