function add(n1: number , n2:number): number {
if (!n2) return n1;
return n1 + n2
}
const a1 = add(1,2)
const a2 = add(10,20,30) // 매개변수는 2개만 올수있음
const a3 = add(10) // 매개변수는 한개만 올수 있음
--------optiaonal parameter 적용 후
//optional parameter
function add(n1: number , n2?:number , n3?:number) : number {
if (!n2) return n1;
return n1 + n2
}
const a1 = add(1,2)
const a2 = add(10,20,30)
const a3 = add(10)
// 숫자형 enum
enum Direction {
Up,
Down = 200,
Left,
Right
}
console.log(Direction.Up,Direction.Down,Direction.Left,Direction.Right) // 0,200,201,202 출력
const up: Direction = Direction.Up; // type을 Direction으로 지정 , Direction의 값들만 올수 있음
const leftOrRight: Direction.Left | Direction.Right = Direction.Left; // Direction.Left or Direction.Right 값만 올 수 있음
//문자형 enum
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
type Hero = {
name: string;
power: number;
height: number;
};
const hero1: Hero = {
name: '슈퍼맨',
power: 1000,
height: 190,
};
const printHero = (hero: Hero) => {
console.log(hero.name, hero.power);
};
printHero(hero1);
기본 사용법
interface Person {
name: string;
age: number;
}
const person1: Person = { name: 'js', age: 20 };
const person2: Person = { name: 'ljs', age: 'twenty' }; // Error
=================================
interface Person1 {
name : string;
age : number;
local ?: string;
}
function hello1(person : Person1) :void {
console.log(`안녕하세요! ${person.name} 입니다.`);
}
const p1 : Person1 = {
name : "Mark",
age : 39
};
hello1(p1);
[참고자료]
한번의 선언으로 다양한 타입에 '재사용'이 가능하다는 장점이 있다.
기본사용법
function helloBasic<T>(message : T) : T {
return message;
}
//generic 설정 두가지
helloBasic<string>("MARK"); // string을 의도해서 인자값에 문자열로만 설정
helloBasic(36); // 들어간 값에 의해서 타입이 추론
배열로 제네릭 지정
function getItemArray<T>(arr: T[], index: number): T {
return arr[index];
}
function pushItemArray<T>(arr: T[], item: T): void {
arr.push(item);
}
const techStack = ['js', 'react'];
const nums = [1, 2, 3, 4];
getItemArray(techStack, 0); // 'js'
pushItemArray<string>(techStack, 'ts'); // ['js', 'react', 'ts']
// pushItemArray<number>(techStack, 123); // Error
getItemArray(nums, 0); // 1
pushItemArray(nums, 5); // [1, 2, 3, 4, 5];
[참고자료]