일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
- 개발콘텐츠
- React.js
- 공통컴포넌트
- react
- 레이아웃쪼개기
- utilty type
- NonNullable
- 커스텀
- 타입선언
- 성능최적화
- 티스토리꾸미기
- typescript
- 타입좁히기
- click and drag
- 폰트적용하기
- JS console
- javascript
- CSS
- 누구나 자료구조와 알고리즘
- const 단언문
- returnType
- 반복줄이기
- Chart.js
- reactjs
- 리액트
- TSDoc
- 2022
- 제네릭
- vue.js
- 타입스크립트
- Today
- Total
목록typescript (20)
몽땅뚝딱 개발자
타입스크립트에서 변수에 값을 당하고 타입을 선언하는 방법은 타입 선언, 타입 단언 2가지 형태가 있다. 📄 사용예제 interface Person { name: string }; // 타입 선언: 그 값이 선언된 타입임을 명시 const alice: Person = { name: 'Alice' }; // 타입 단언: 타입스크립트가 추론한 타입이 있더라도 Person 타입으로 간주 const alice = { name: 'Alice' } as Person; ◽ 타입 선언 타입 선언은 할당되는 값이 해당 인터페이스를 만족하는지 검사한다. 아래 예제에서는 Person에 맞는 속성이 없기떄문에 타입스크립트에서 오류를 표시한다. // 타입 선언 const alice: Person = {}; // error: 'P..
◽ Exclude T에 지정된 타입들 중 U에 나열된 타입들은 제외하여 정의한다. /** * Exclude from T those types that are assignable to U */ type Exclude = T extends U ? never : T 예제 1. type TChar = "a" | "b" | "c" | "d" type T00 = Exclude; // "b" | "d" 예제 2. interface IUser { name: string age: number birth: Date death: Date } type User = Exclude // type User = "name" | "age" | "birth" ◽ Extract // Extract: T에 지정된 타입들 중 U에 나열된 타..
◽ 제네릭 사용하기 function logText(text: T):T { console.log(text); return text; } logText('안녕') ◽ 제네릭의 장점 유니온을 사용하는 경우 명확한 변수타입이 지정되지않아 생기는 문제들이 있었다. 제네릭은 호출시점에 타입을 지정하므로 이런 문제점을 해결할 수 있다. function logText(text: T):T { console.log(text); return text; } logText('안녕') logText(123) logText(true) ◽ 제네릭 적용하기 [before] // 이렇게 선언하는 경우 type에 따라 여러개의 인터페이스를 만들어주어야 한다. // 유지보수면에서 효율성이 떨어진다. interface DropdownStr ..
◽ 이넘(enum)이란? 이넘은 특정 값들의 집합을 의미하는 자료형이다. ◽ 예제 숫자형 이넘을 살펴보자. enum Shoes { Nike, // 0 Adidas // 1 } const shoes = Shoes.Nike; console.log(shoes); // 0 문자형 이넘을 살펴보자. enum Shoes { Nike = '나이키', Adidas = '아디다스' } const shoes = Shoes.Nike; console.log(shoes); // '나이키' ◽ enum을 사용해보자 enum Answer { Yes = 'Y', No = 'N' } function askQuestion(answer: Answer) { if(answer === Answer.Yes) { console.log('정답입..
◽ 유니온 타입 여러가지의 타입을 파이브로 연결하여 지정할 수 있다. // 변수에 사용하기 const user = string | number // 함수에 사용하기 function logMessage(value: string | number) { console.log(value); } logMessage('hello') logMessage(10) 📄 예제 // 유니온 타입 function logMessage(value: string | number) { if(typeof value === 'number') { value.toLocaleString() } if(typeof value === 'string') { value.toString() } throw new TypeError('value must be..
◽ 예제 인터페이스는 '상호간의 약속'으로 특정 형식으로 지정해준다. interface User { age: number; name: string; } 변수에 인터페이스를 활용해보자. const thor: User = { age: 50000, name: '토르' } 함수에 인터페이스를 활용해보자. // 함수에 인터페이스 활용 function getUser(user: User) { console.log(user); } API의 스펙을 지정하는 것에 가장 많이 사용한다. // 함수의 스펙(구조)에 인터페이스를 활용 interface SumFunction { (a: number, b: number): number; } let sum: SumFunction; sum = function (a: number, b:..
각 변수에 *타이핑(Typing) 한다. * 타이핑(Typing): 타입이 정의되지 않은 코드에 타입을 입혀주는 행위 📄 문자열 // JS const str = 'hello'; // TS const str:string = 'hello' 📄 숫자 // JS const num = 1 // TS const num:number = 1 📄 배열 // JS const arr = [1, 2, 3]; // TS const arr: Array = [1, 2, 3]; const arr:number[] = [1, 2, 3]; 📄 튜플: 길이와 타입이 고정된 배열 // TS // 모든 index의 타입이 지정되어있는 배열 let address: [string, number] = ['강남', 1]; 📄 객체 // TS let ..
◽ 테스트 사이트 TS Playground - An online editor for exploring TypeScript and JavaScript The Playground lets you write TypeScript or JavaScript online in a safe and sharable way. www.typescriptlang.org ◽ 코드 변환해보기 class Student { name: string; constructor(name: string) { this.name = name; } } 📄 ES5로 변환 "use strict"; var Student = /** @class */ (function () { function Student(name) { this.name = name; }..
📄 tsconfig.js { "compilerOptions": { "allowJs": true, "checkJs": true, // 모든 타입에 대해 최소한 any라도 지정해야한다는 옵션 "noImplicitAny": true } } /** checkJs는 // @ts-check 와 같은 기능을 한다. */ 다른 옵션은 여기서 확인해보자! TSConfig Reference - Docs on every TSConfig option From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project. ..
◽ 타입스크립트란? 자바스크립트에 타입을 부여한, 자바스크립트의 확장된 언어이다. 브라우저에서 실행하기 위해 파일을 한 번 변환해주어야하는데 이것을 컴파일이라고 한다. ◽ 타입스크립트를 사용하는 이유 에러의 사전방지와 자동완성을 손쉽게 하기 위함이다. // Address는 Obejct 타입으로 객체로 한번 더 지정해 줌! // 하지만 이렇게 쓰는건 재활용과 가독성 관점에서 추천하지 않는다. /** * @typedef {object} Address * @property {string} street * @property {string} city */ /** * @typedef {object} User * @property {string} name * @property {string} email * @prop..