👵 과거의 TypeScript
"TypeScript는 JavaScript의 Super Set이다"
= typescript가 javascript를 포함하고 있다.
👩 현대의 TypeScript
"TypeScript is JavaScript with syntax for types."
👉 타입 구문이 있는 JavaScript
JavaScript and More | A Result You Can Trust | Safety at Scale |
▪ JavaScript에 추가 구문 ▪ IDE와 통합 ➡ 오류 캐치 |
▪ JavaScript로 변환 ▪ JavaScript가 지원되는 모든 곳에서 실행 (브라우저, Node.js, Deno 등) |
▪ JavaScript를 이해하는 타입 추론을 사용 ▪ 추가적인 코드 없이도 훌륭한 도구를 제공 |
IDE와 통합 : microsoft 회사에서 typescript와 vs code를 만들었기 때문에 둘의 호환성이 굉장히 좋다.
😎 TypeScript 인기
npm trends, state of js 라는 사이트에서 확인할 수 있다.
react와 vue를 넘은 인기를 볼 수 있다.
Stack Overflow
TypeScript가 JavaScript보다 사용률이 더 높다.
💪 TypeScript 효과
(나의, 우리의) 데이터 기술서
- 객체와 함수의 생김새를 정의
- 데이터를 코드로 설명할 수 있는 데이터 기술서
- 편집기에서 문서 및 버그를 검출할 수 있습니다.
interface Person{
name: string;
age: number;
gender: 'M' | 'F';
};
나를 데이터로 표현한다면 다음과 같다.
const Plum = {
name: '자두';
age: 24;
gender: 'F';
};
이것은 나만의 데이터 기술서이다.
우리는 interface로 어떤 타입을 사용할 것인지 설명할 수 있다.
데이터 기술서에 대한 효과를 살펴보겠다.
JavaScript 파일
function compact(arr){
if(orr.length > 10)
return arr.trim(0, 10)
return arr
}
위의 코드는 JavaScript 파일에 편집기 경고가 없지만, 런타임에 충돌한다.
🏃♀️ JavaScript 런타임 시점 오류 검출
이때,
@ts-check
를 위에 달아주면 편집기에 오류가 표시된다.
🤷♀️ 어떻게 오류를 검출할 수 있을까?
@ts-check을 하게 되면 JavaScript 코드를 Block scope이나 Function scope로 동작시킬 수 있다.이때, orr이라는 변수는 이 block scope 안에 선언되어 있지 않은 변수이다.그러므로 오류를 검출 할 수 있게 된다.
또 다른 에러를 보자.
@param {any[]} arr
JSDoc을 사용하여 타입에 대한 정보를 제공할 수 있다.
trim()은 문자열 양 끝에 공백을 제거하는, 문자열에만 사용할 수 있는 메서드이기 때문에 오류가 발생한다.
🙆♂️ TypeScript (타입 구문 추가)
결론적으로, 올바른 코드는 아래의 코드이다.
function compact(arr: string[]){
if(arr.length > 10)
return arr.slice(0, 10)
return arr
}
arr라는 인자에 string[] 타입을 추가한 것이다.
🤼♂️ JavaScript와 TypeScript의 차이
타입 구문이 존재하는 JavaScript, 즉 TypeScript이며 TypeScript가 컴파일 되면 JavaScript로 변환된다.
아래의 TypeScript 코드가
type Result = "pass" | "fail"
function verify(result: Result){
if(result === 'pass'){
console.log("Passed")
}else{
console.log("Failed")
}
}
아래의 JavaScript 코드로 변환된다.
function verify(result){
if(result === 'pass'){
console.log("Passed")
}else{
console.log("Failed")
}
}
컴파일이 되면서 type부분이 삭제되는 것을 볼 수 있다.
🚀 TypeScript 미래
이미 현재 진행형에 가까움
국내 Front-end 채용 공고
그리고 놀라운 뉴스가 발표되었다.
기존에 TypeScript를 JavaScript로 컴파일해서 브라우저에 동작하는 방법에서
JavaScript에 바로 Types를 추가해서 브라우저에 동작하도록 만드는 것을 제안했다고 발표가 되었다.
출처 : https://devblogs.microsoft.com/typescript/a-proposal-for-type-syntax-in-javascript/
A Proposal For Type Syntax in JavaScript
Today we’re excited to announce our support and collaboration on a new Stage 0 proposal to bring optional and erasable type syntax to JavaScript. Because this new syntax wouldn’t change how surrounding code runs, it would effectively act as comments. W
devblogs.microsoft.com
실제로 tc39에 Stage1으로 등재가 되어있다.
출처 : https://github.com/tc39/proposal-type-annotations
GitHub - tc39/proposal-type-annotations: ECMAScript proposal for type syntax that is erased - Stage 1
ECMAScript proposal for type syntax that is erased - Stage 1 - GitHub - tc39/proposal-type-annotations: ECMAScript proposal for type syntax that is erased - Stage 1
github.com
💡 TypeScript 의식적으로 학습하기
❌ any 지양하기
any를 사용하면 TypeScript보다 JavaScript에 가깝다.
any를 대체할 수 있는 타입들
- unknown
- Generic
- Type Guard
- Type Assertion
- ban-ts-comment (es-Lint 규칙)
@ts-expect-error
@ts-ignore
@ts-nocheck
@ts-check
TypeScript ESLint
Tooling which enables ESLint to support TypeScript
typescript-eslint.io
⭕ 지향하기
- strictNullChecks
- ts-config에서 설정 가능
- 문서화
- 내가 작성하는 typescript 코드를 문서화 하자.
- 선 타이핑 후 구현
- 타입스크립트에 타입을 먼저 달고 그것에 맞게 구현을 하는 것이 좋다.
- 집단지성
- 구글링 많이 하고, 찾아보고, 공유하자.
- 컨벤션 & 팀 문화 지향하기
- eslint와 wiki를 참고하면 좋다.
- 오픈소스 : https://github.com/basarat/typescript-book/blob/master/docs/styleguide/styleguide.md
- google : https://google.github.io/styleguide/tsguide.html
- microsoft wiki : https://github.com/microsoft/TypeScript/wiki
- eslint : https://typescript-eslint.io/
GitHub - basarat/typescript-book: The definitive guide to TypeScript and possibly the best TypeScript book . Free and Open Sourc
:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹 - GitHub - basarat/typescript-book: The definitive guide to TypeScript and possibly t...
github.com
Google TypeScript Style Guide
Google TypeScript Style Guide TypeScript style guide This is the external guide that's based on the internal Google version but has been adjusted for the broader audience. There is no automatic deployment process for this version as it's pushed on-demand b
google.github.io
GitHub - microsoft/TypeScript: TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output. - GitHub - microsoft/TypeScript: TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
github.com
TypeScript ESLint
Tooling which enables ESLint to support TypeScript
typescript-eslint.io
💨 TypeScript playground 소개
TypeScript 공식 사이트 : https://www.typescriptlang.org/
JavaScript With Syntax For Types.
TypeScript extends JavaScript by adding types to the language. TypeScript speeds up your development experience by catching errors and providing fixes before you even run your code.
www.typescriptlang.org
PlayGround 카테고리를 들어가면
- VS code가 내장되어 있기 때문에 단축키를 사용할 수 있다.
- TS Config에서 설정하여 JavaScript 코드를 만들 수 있다.
- 실행도 할 수 있다.
- code sandbox로 코드를 열어볼 수 있다.
- vs code로 열어볼 수 있다.
- AST Viewer로 추상 구문 트리로, 내부적으로 어떤 언어가 사용되고 있는지 확인할 수 있다.
- 많은 플러그인을 추가할 수 있다.
- 코드를 ctrl + s 로 저장하고 share를 누르면 코드 url를 공유할 수 있다.
이런 PlayGround에서 TypeScript를 공부하는 것을 추천한다.
'TypeScript' 카테고리의 다른 글
[TypeScript] 기본 타입 (0) | 2022.09.13 |
---|
Comment