typescript 関数を定義する
- 作成日 2021.01.03
- TypeScript
- TypeScript

typescriptで、関数を定義するサンプルコード記述してます。typescriptのバージョンはVersion 4.1.2となります。
環境
- OS windows10 64bit
- typescript Version 4.1.2
関数を定義
typescriptでは、以下のように関数を定義することが可能です。
引数なし、戻り値なし
function hello(){
console.log('hello')
}
console.log(hello()); // hello
引数あり、戻り値なし
function disp(str: string): void {
console.log('hello' + str)
}
console.log(disp('world')); // helloworld
// voidは省略可能
function disp(str: string) {
console.log('hello' + str)
}
引数あり、戻り値あり
function calc(num: number): number {
return num + num;
}
console.log(calc(1)); // 2
console.log(calc(2)); // 4
引数があってもなくてもいいような場合は「?」を使用します。
function disp(str?: string) {
(str) ? console.log('hello' + str) : console.log('hello')
}
console.log(disp()); // hello
引数にデフォルトの値を指定することも可能です。
function disp(str: string = 'world') {
console.log('hello' + str)
}
console.log(disp()); // helloworld
無名関数やアロー関数も使用可能です。
const hoge = function(x: number, y: number) { return x + y; }
console.log(hoge(1,2)) // 3
const foo = (x: number, y: number) => { return x + y; }
console.log(foo(1,2)) // 3
-
前の記事
React.js ライブラリ「react-typewriter-effect」を使ってタイプライティングを実装する 2021.01.03
-
次の記事
docker composeで「NiFi」を構築するまでの手順 2021.01.03
コメントを書く