TypeScript 기본 개념
2020. 10. 4. 16:29ㆍDEV/TypeScript
반응형
Types
- 변수의 타입을 지정해주어 누구나 알 수 있도록 설정
- 가변형으로 사용하고자 할 경우 변수에 ?를 추가하면 Optional로 설정됨
- return type : (...변수) : [반환 타입 지정]
const sayHello = (name: string, age: number, gender?: string): void => {
console.log(`Hello ${person.name}, you are ${person.age}, you are a ${person.gender}!`);
}
Enum
[REF] TypeScript enum을 사용하는 이유
- 특정 고정값들을 저장
- 항상 리터럴 타입이 사용됨
- 속성값 : 문자열, 숫자만 허용
export enum LanguageCode {
korean = 'ko',
english = 'en',
japanese = 'ja',
chinese = 'zh',
spanish = 'es',
}
emum 자체가 Object로 작동한다.
const keys = Object.keys(LanguageCode) // ['korean', 'english', ...]
const values = Object.values(LanguageCode) // ['ko', 'en', ...]
Interface
- 객체를 주입하고자 할 때 사용
- JavaScript로 컴파일 되지 않음
interface Human {
name: string;
age: number;
gender: string;
}
const person = {
name: "Jake",
age: 22,
gender: "male"
};
const sayHi = (person: Human): string => {
return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}!`;
};
Class
- JavaScript로 변환 필요 시 사용 eg. React, Express, Node 등 사용 시
- 클래스의 속성(Property)를 선언해야 함
- 권한(Permmision)도 설정
- public
- private : 클래스 내부에서만 접근 가능
class Human {
public name: string;
public age: number;
public gender: string;
static sayHello(name: string): string => {
return `Hello, ${name}!`;
}
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
const person = new Human("Miky", 20, "Female");
Function
- static function : 클래스를 생성하지 않고도 외부에서 사용 가능
반응형
'DEV > TypeScript' 카테고리의 다른 글
TypeScript 기본 설정 (0) | 2020.10.04 |
---|