목록TypeScript (11)
개발블로그
keyofinterface User8 { id: number; name: string; age: number; gender: "m" | "f";}type UserKey9 = keyof User8; // 'id' | 'name' | 'age' | 'gender'// const uk: UserKey9; // Errorconst uk: UserKey9 = "name";// UserKey9 안에 키값중에 하나를 입력하면 에러가 안난다.partial프로퍼티를 모두 옵셔널로 바꿔준다.일부만 사용이 가능하다.interface User7 { id: number; name: string; age: number; gender: "m" | "f";}// Error/*let admin: User7 = { id..
타입을 구성할 수 있는 방법 중 하나이다.유니언 타입or, |교차 타입and, &유니언 타입(Union Types)두 타입 중 하나만 사용해도 된다.동일한 속성에 타입을 다르게해서 구분할 수 있는걸 식별 가능한 유니언 타입이라고 한다.name이라는 동일한 타입을 줘서 두개의 인터페이스를 유니언 타입으로 사용이 가능하다.// Union Typesinterface Car { name: "car"; color: string; start(): void;}interface Mobile { name: "mobile"; color: string; call(): void;}function getGift(gift: Car | Mobile) { console.log(gift.color); if (gift.n..
Literal Types집합 타입의 보다 구체적인 하위 타입// "Hello World" == string// string !== "Hello World"문자열과 숫자 두가지 리터럴 타입이 있는데 이를 사용하면 문자열이나 숫자에 정확한 값을 지정할 수 있다.// Literal Typesconst userName1 = "Bob";// userName1은 string이긴 하지만 const로 값을 변할 수 없어// userName1에 마우스를 가져다대도 "Bob"가 나온다.let userName2 = "Tom";// userName2는 let으로 값이 변할 수 있어// 마우스를 가져다대면 string가 나온다.// 만약 userName2에 숫자를 넣고 싶다면// let userName2: string | nu..
참고 TypeScript - Class | PoiemaWebES6에서 새롭게 도입된 클래스는 기존 프로토타입 기반 객체지향 언어보다 클래스 기반 언어에 익숙한 개발자가 보다 빠르게 학습할 수 있는 단순명료한 새로운 문법을 제시하고 있다. 하지만poiemaweb.comES6 클래스는 클래스 몸체에 메소드만 포함할 수 있다.클래스 몸체에 클래스 프로퍼티를 선언할 수 없고 반드시 생성자 내부에서 클래스 프로퍼티를 선언하고 초기화를 해줘야한다.예시// 잘못된 예시class Person { constructor(name) { // 클래스 프로퍼티의 선언과 초기화 this.name = name; } walk() { console.log(`${this.name} is walking`); ..
Generics제네릭은 타입스크립트에서 함수, 클래스. interface, type을 사용하게 될 때 여러 종류의 타입에 대하여 호환을 맞춰야 하는 상황에서 사용하는 문법이다.함수에서 Generics 사용하기// 예시function merge(a: any, b: any): any { return { ...a, ...b };}const merged = merge({foo: 1}, {bar: 1});// 객체 A와 객체 B를 합쳐주는 merge라는 함수를 만든다고 가정// A와 B가 어떤 타입이 올 지 모르기 때문에 이런 상황에서는 any 타입 사용 가능// any = 모든 데이터 타입을 허용// 이렇게 하면 타입추론이 모두 깨진것과 다름이 없다.// 결과가 any 라는 것은 merged 안에..
Type은 특정 타입에 별칭을 붙이는 용도로 사용하고 있다.사용하여 객체를 위한 타입을 설정할 수도 있고, 배열 또는 그 어떤 타입이던 별칭을 지어줄 수 있다.type Person1 = { name: string; age?: number;};// &는 Intersection 으로서 두개 이상의 타입들을 합쳐준다.// 참고: https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-typestype Developer1 = Person1 & { skills: string[];};const person2: Person1 = { name: '김사람'};const expert2: Developer1 = { name: '김개..
클래스 또는 객체를 위한 타입을 지정 할 때 사용되는 문법이다.클래스에서 interface를 implements하기클래스를 만들 때, 특정 조건을 준수해야 함을 명시하고 싶을 때 interface를 사용하여 클래스가 가지고 있어야 할 요구 사항을 설정클래스를 선언 할 때 implements 키워드를 사용하여 해당 클래스가 특정 interface의 요구사항을 구현한다는 것을 명시// Shape 라는 interface를 선언interface Shape { getArea(): number; // Shape interface 에는 getArea 라는 함수가 꼭 있어야 하며 해당 함수의 반환값은 숫자이다.}class Circle implements Shape { // 'implements' 키워드를 사용하여..
예시function sum(x: number, y: number): number { return x + y;}sum(1, 2);// (): number 부분이 해당 함수의 결과물이 숫자라는 것을 명시해준다.Errorfunction sum(x: number, y: number): number { return null;}sum(1, 2);sumArray 함수function sumArray(numbers: number[]): number { return numbers.reduce((acc, current) => acc + current, 0);}const total = sumArray([1, 2, 3, 4, 5]);function returnNothing(): void { console.log('I am..