Development Study/Frontend
[TypeScript] TypeScript Grammar - 06~07
TMInstaller
2023. 1. 8. 01:37
728x90
Previous Series
6. Functions
This Posting contains how to make functinos in TypeScript
6_01. Functions_return type
When contains void
function add(n1: number, n2: number):void{
console.log(n1 + n2);
}
When contains return type
function add(n1: number, n2: number):void{
return (n1 + n2);
}
function time(minute: number):boolean{
return num = 60;
}
function functionTest (x: number): number{
return x*3;
}
functionTest(2);
functionTest('10'); // not number value, error
6_02. Functions_with optional
import { log } from "console";
function hello(name ?: string){
return `hello, ${name || "world"}`;
}
const result = hello();
const result2 = hello("Sam Rider");
log(result); // hello, world
log(result2); // hello, Sam Rider
I think that part of "${name || 'world'}" may be show 'world' when the name's type is different from the setting
7. Loop
Maybe you are familiar with this, because in Python, there is a 'for loop' and it is similar
7_01. Loop_let ... in
array
import { log } from 'console';
let list: string[] = ['test1', 'test2', 'test3'];
for (let i in list){
log(i, list[i]);
}
Q. Can we do the type designation on the following list?
import { log } from 'console';
let animals: any = {a: 'rat', b: 'cat', c: 'tiger'}
for (let anim in animals){
log(anim, animals[anim]);
}
A. Of course No
7_02. Loop_let ... of
import { log } from 'console';
let str: string = "hello";
for (const a of str){
log(a);
}
End
Next Series
728x90