
// 문자열
const str: string = 'hello';
// 숫자
const num: number = 10;
// 배열
const arr: Array<number> = [1, 2, 3];
const heroes: Array<string> = ['Capt', 'tor'];
const items: number[] = [1, 2, 3];
// 튜플
const tuple: [string, number] = ['haha', 1];
// 객체
const obj: object = {};
const person: { name: string; age: number } = {
name: 'thor',
age: 1000
};
// boolean
const show: boolean = true;
// undefined, null
let mightBeUndefined : string|undefined = undefined;
let nullableNumber : number|null = null;
// | 연산자
let color:'red'|'orange'|'yellow' = 'red';
color = 'yellow'; //color = 'green';
함수 타입은 파라미터와 반환값에 타입을 정의한다.
return type이 없으면 void 함수
function sum(a: number, b: number):number { return a + b; } sum(10, 20);
파라미터를 제한하는 특성으로 파라미터의 갯수나 타입을 체크한다

optional parameter : 파라미터에?를 붙이면 파라미터가 없어도 에러가 나지 않는다.

interface는 클래스 또는 객체 를 위한 타입을 지정 할 때 사용하는 문법
// 인터페이스 정의
interface User{
age:number;
name:string;
}
// 변수 정의
var saram1:User = {
age:33,
name:'세호'
}
// 함수의 인자 정의
function getUser(user:User){
console.log(user);
}
getUser(saram1)
interface SumFunction{
(a:number,b:number):number;
}
let sum: SumFunction;
sum = function(a,b,){
return a+b
}
interface StringArray{
[index:number]:string;
}
const arr:StringArray = ['a','b','c']
// indexing
arr[0] = 'd'
interface StringRegexDictionary{
[key:string]:RegExp // 정규표현식
}
const obj:StringRegexDictionary = {
sth:/abc/, // 통과
sss:'abc', // 에러
}
interface Person{
name:string;
age:number;
}
interface Developer extends Person{
language:string;
}
const me:Developer = {
name:'Gisele',
age:30,
language:'javascript'
}
string,number와 같은 간단한 타입 뿐 아니라 interface 레벨의 복잡한 타입에도 별칭을 부여할 수 있다.type Person = {
name:string;
age:number;
}
const seho:Person={
name:'세호',
age:30
}
| Inferace | Type | |
|---|---|---|
| 확장 🌷 | 가능 | 불가능 |
| 재할당 | 가능 | 불가능 |
| 목적 | 구현 | 데이터를 담기 |
좋은 소프트웨어는 확장이 용이해야하기 때문에 type보다는 interface로 선언해서 사용하는 것을 추천
하나 이상의 타입을 쓰고 싶을 때, | 연산자를 이용해 여러 연산자를 여러 개 연결할 수 있다. (or의 의미)
function logMessage(value:string| number){ // union type
if(typeof value==='number'){
console.log(value.toLocaleString())
}
if(typeof value==='string'){
console.log(value.toLowerCase())
}
throw new TypeError('value must be string or number')
}
타입 추론이 되기 때문에 아래와 같이 해당 타입에 대한 자동완성 기능을 이용할 수 있다.


interface 두 개를 합쳤을 때, 공통된 속성에만 접근할 수 있다.

여러 타입을 모두 만족하는 하나의 타이블 의미한다.


이넘은 특정 값들의 집합을 의미하는 자료형이다.
이넘을 선언하고 별도의 값을 지정하지 않으면 숫자형 이넘으로 0부터 1씩 증가한다.
// 숫자형 이넘
enum Shoes{
Nike, //0
Adias, //1
NewBalance//2
}
const myShoes = Shoes.Nike
console.log(myShoes); // 0
// 문자형 이넘
enum Shoess{
Nike = '나이키',
Adias = '아디다스',
NewBalance = '뉴발란스'
}
const myShoes = Shoess.Nike
console.log(myShoes); //나이키

위와 같이 string type으로 타입을 정의할 경우 yes,no가 아닌 다른 값도 들어와서 예외처리를 할 수 없다. Enum type을 사용하면 지정한 값이 아닌 다른 값에 대해 미리 에러가 발생한다.
📑 referece