
npm install typesciprt -gtsc 파일이름.tsnpm install ts-node -g)후 실행(ts-node 파일이름.js)number stringnumber[], Array<string>, (string|boolean|number)[] 등objectnull, undefinedlet num1: number = 0; // 숫자
let str1: string = 'hi'; // 문자열
const TRUE: boolean = true; //boolean
//숫자 배열
let numbArr1: number[];
let numArr2: Array<number>;
//문자배열
let strArr1: string[];
let strArr2: Array<string>;
//여러 타입이 들어가는 배열
let variatyArr1: (number | string | object)[] = ['aa', 'bb', 0];
let variatyArr2: Array<number | boolean | string> = [true, 'hihi', 10];
//어떤 사료형이던 상관 없는 배열
let anyArr: any[];
//객체
let object: object = {
id: '2013',
name: '양갱',
};
//null
let nonono: null = null;
let HIHI: undefined;
readonly를 사용하여 고정let lunch: [string, number];
lunch = ['salad', 2];
console.log(lunch); // [ 'salad', 2 ]
lunch.push('pasta');
//배열값을 고정시키려고 사용하였는데 길이가 변함
console.log(lunch); // [ 'salad', 2, 'pasta' ]
//readonly를 사용하여 길이 고정
let lunch: readonly [string, number];
lunch = ['salad', 5];
console.log(lunch);
enum Direction {
Up = 1, //Up을 1로 초기화하면 뒤에는 2,3,4 ... 자동으로 할당
Down,
Left,
Right,
}
enum Direction2 {
Up, //초기값을 정해주지 않는다면 0으로 할당후 1씩증가
Down,
Left,
Right
}
enum UserResponse {
No = 0,
Yes = 1,
}
function respond(recipient: string, message: UserResponse): void {
// 열거형이름을 type으로 선언해 사용가능
}
respond("Princess Caroline", UserResponse.Yes);
enum E {
A = getSomeValue(),
B, // 오류! 앞에 나온 A가 계산된 멤버이므로 초기화가 필요합니다.
//Enum member must have initializer.
}
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "Left",
Right = "Right",
}
enum BooleanLikeHeterogeneousEnum {
No = 0,
Yes = "YES",
}
참고 : typescriptlang.org
let anyType:any ;
anyType = 1;
anyType = "HI";
anyType = [1,2,3]
interface Student {
name: string;
isPassed: boolean;
}
const student1: Student = {
name: '양갱',
isPassed: true,
};
enum Score {
Aplus = 'A+',
A = 'A',
Bplus = 'B+',
B = 'B',
Cplus = 'C+',
C = 'C',
}
interface CollegeStudent extends Student {
major: string;
readonly id: number;
[grade: number]: Score; // 학년 : 점수
club?: string; // ?는 있어도 되고 없어도 됨
}
const yangGang: CollegeStudent = {
name: '남양갱',
major: '전자공학',
isPassed: true,
id: 2013,
1: Score.A,
2: Score.Aplus,
};
yangGang.club = 'coomroom';
//yangGang.id = "2017"; readonly로 error
console.log(yangGang);
interface HumanInterface {
name: string;
age: number;
}
type HumanType = {
name: string;
age: number;
};
let human1 :HumanInterface = {
name : "사람1",
age : 20,
}
let human2 : HumanType = {
name : "사람2",
age : 20,
}
type Gender = 'F' | 'M';
type Person = {
name: string;
age?: number;
like?: string[];
gender: Gender;
};
let daniel: Person = {
name: '양갱',
gender: 'F',
};
// 문자열 리터럴로 타입 지정
type Str = "Lee";
// 유니온 타입으로 타입 지정
type Union = string | null;
// 문자열 유니온 타입으로 타입 지정
type Name = "Lee" | "Kim";
// 숫자 리터럴 유니온 타입으로 타입 지정
type Num = 1 | 2 | 3 | 4 | 5;
// 객체 리터럴 유니온 타입으로 타입 지정
type Obj = { a: 1 } | { b: 2 };
// 함수 유니온 타입으로 타입 지정
type Func = (() => string) | (() => void);
// 인터페이스 유니온 타입으로 타입 지정
type Shape = Square | Rectangle | Circle;
// 튜플로 타입 지정
type Tuple = [string, boolean];
const t: Tuple = ["", ""]; // Error
|를 이용해 사용let age : string | number; //string이나 number가 될 수 있음을 명시
function nextYearAge(age:number | string) {
if(typeof age === 'number') { //type을 구분하여 분기처리
console.log(`내년에는 ${age+1}살 입니다.`)
} else {
console.log(`내년에는 ${Number(age) +1 }살 입니다.`)
}
}
type Common = {
name: string;
age: number;
gender: string;
};
type Animal = {
howl: string;
};
type Cat = Common & Animal; // 교차타입
type Dog = Common | Animal; // union타입
let dog: Dog = { // 둘중 하나만 만족하면되지만
howl: '멍멍멍',
};
let cat: Cat = { //둘 모두 만족해야한다
age: 1,
gender: 'F',
name: '나비',
howl: '이야아아아아아아옹',
};
function data<T>(arr: T[]) { //어떤 배열이 넘어올지 모를때 generic으로 선언 후.
return arr.length;
}
console.log(data<number>([1, 2, 3])); //함수호출 시 타입 지정
console.log(data<string>(['a', 'b', 'c']));
function print<T, U>(x:T, y:U){ //각각 지정도 가능, 두개가 같은 타입이면 같은 문자 사용하면됨
console.log(x,y)
}
print<string, number>("HIHI",1234);
interface Product<T>{ // interface에서도 generic 사용 가능
company : string;
createdAt : Date;
option : T;
}
type phoneOption = {
size : string
}
type noteBookOption = {
inch : number
}
const iphone:Product<phoneOption> = {
company : "apple",
createdAt : new Date("2024-03-23"),
option : {
size : "pro"
}
}
const macBook : Product<noteBookOption> = {
company : "apple",
createdAt : new Date("2024-03-23");
option : {
inch : 13
}
}