[typescript] 맛보기

Yeonjoo Yoo·2022년 1월 28일
0

TIL

목록 보기
5/12
typescript에 대해서 간단하게 정리하려고 한다.

  • stackoverflow survey

Dynamic Typing in JS

동적 타입 언어 란?

  • 런타임 시 타입이 결정됨
  • 타입 없이 변수만 선언하여 값을 지정할 수 있음
let a = 'str'; // string
a = 1; // number

장점

  • 런타임까지 타입에 대한 결정을 끌고 갈 수 있기 때문에 유연성이 높음
  • 컴파일시 타입을 명시해주지 않아도 되기 때문에 상대적으로 코드가 짧고 빠르게 작성 가능
  • Learning-Curve가 낮음

단점

  • 실행 도중에 예상치 못한 TypeError 발생할 수 있음
  • 런타임 중에 타입 체크가 일어나기 때문에 performance cost가 발생

Type checking

  1. //@ts-check in VSCode (IntelliSense)
//@ts-check

let str = 'this is string';
//str = 1; // Error!

/**
 * @param { number } a 첫 번째 숫자
 * @param { number } b 두 번째 숫자
 * @returns { number } 합산
 */
 const sum = (a, b) => a + b;

 const result = sum(1 , 2);
 console.log(result);
  • JSDoc : Javasript 소스코드 파일에 주석을 달기위해 사용되는 마크업언어
/**
 * Represents a book.
 * @param {string} title 책 제목
 * @param {number} series 책 순서
 * @param {string} author 책 작가
 * @returns { string } 책 제목
 * @description 책 제목 반환 함수
 */
function getBookTitle(title, series, author) {
  return `${title} ${series} (${author})`;
}
  1. Typescript
  2. 기타 다른 라이브러리
    • flow in React

Typescript(TS)

타입스크립트 란?

  • 자바스크립트에 타입을 부여하여 확장된 언어 (Superset)
  • MS에서 개발하고 관리하는 오픈소스 프로그래밍 언어
  • 파일 확장자 '.ts'
  • 타입스크립트를 실행시키기 위해 compile 과정 필요함
    • 컴파일 시, 동일 이름을 가진 js 파일 생성 (.ts -> .js)

특징

  • 에러의 사전 방지 가능 (안정성 보장)
  • vscode와 함께 사용 시, 코드 가이드 및 자동 완성 기능 활용하여 개발 생산성을 향상 (VSCode intelliSense)

tsc 명령어

typescript 라이브러리 설치

  • npm i typescript -g (전역 설치)
    • tsc 명령어 사용 가능
    • 'C:\Users{사용자명}\AppData\Roaming\npm'에 tsc가 설치됨 (local system level)
  • ts 파일을 js 파일로 compile 가능
    • tsc <파일명.js>
  • tsc 명령어에 직접 컴파일에 필요한 옵션을 추가하거나 tsconfig.json 파일로 설정 가능
    • tsc -h 으로 옵션 확인

tsconfig.json

  • 타입스크립트를 자바스크립트로 변환할 때의 설정을 정의해놓는 파일
{
  "compilerOptions": {
    // .js 파일을 .ts로 인식해서 그대로 쓰겠다
    "allowJs": true,
    // @ts-check와 동일한 효과
    "checkJs": true,
    // tsc 명령어로 변경할 js문법
    "target": "es5",
    // ts 결과물이 들어갈 경로
    "outDir": "./dist",
  },
  // 프로젝트를 기준으로 어떤 폴더를 대상으로 ts를 컴파일 시킬 것인가
  "include": ["./src/**/*"],
  "exclude": ["node_modules", "dist"],
}

예제

// 기본 문법
// 1. 문자열, 숫자, 불리언
const str1: string = 'hi'
const num: number = 1
const show: boolean = true

// 2. Array
const arr1: Array<number> = [1, 2, 3]
const arr2: string[] = ['1', '2', '3']

// 3. Object
const obj: object = {}
const person: {name: string, age: number} = {
  name: 'emma',
  age: 10
}

// 4. interface
// 인터페이스는 ES6가 지원하지 않는 타입스크립트만의 특징
// 다중 상속 가능
// 인터페이스는 타입이며 컴파일 후에 사라짐
interface Empty {}

interface Person {
  name: string;
  age: number;
}

interface Developer extends Person, Empty {
  skills: Array<string>;
}

const emma: Developer = {
  name: '유연주',
  age: 30,
  skills: ['js', 'ts', 'etc..']
}

// 5. Generics
function identity<T>(arg: T): T {
  return arg
}
const i = identity<string>('str')


interface Items<T> {
  value: T;
  selected: boolean;
}
const emails: Items<string>[] = [
  { value: 'socks', selected: true },
  { value: 'shoes', selected: false },
]

// 기타 용어
// 1. Type Guard
// 특정 타입으로 타입의 범위를 좁혀나가는 과정
function getValue(val: string | number) {
  //val.
  if(typeof val === 'string') {
    return val.replace(' ', '')
  }
  if(typeof val === 'number') {
    return val.toFixed(2)
  }
}
const gv = getValue('A B C')
console.log(gv)

// 2. Type Compatibility (타입 호환)
interface Kevin {
  name: string;
}

interface Steve {
  name: string;
}

let kevin: Kevin = { name: 'kevin'};
let steve: Steve = { name: 'steve'};
kevin = steve; // OK, structural typing or duck typing
// "Duck typing" : 만약 어떤 새가 오리처럼 걷고, 헤엄치고, 
// 꽥꽥거리는 소리를 낸다면 나는 그 새를 오리라고 부를 것이다.

// 3. Operator

interface A { a: string, b: any }
interface B { b: any, c: number }
// 3-1. Union Type (|)
const union: A | B = { b: false, c: 1 }

// 3-2. Intersection Type (&)
const intersection: A & B = { a: 'str', b: false, c: 1 }
let test: string & number & boolean

// 3-3 Non-Null Assertion (!)
// --strictNullChecks 를 사용하지 않는다면 권장하지 않음
let text
const span = document.querySelector('span')
text = span!.innerText

// 3-4.Optional Chaining (?)
text = span?.innerText

참고
https://insights.stackoverflow.com/survey
https://www.typescriptlang.org
https://en.wikipedia.org/wiki/JSDoc
https://jsdoc.app/
https://code.visualstudio.com/docs/nodejs/working-with-javascript#_intellisense
https://velog.io/@eunnbi/%EC%A0%95%EC%A0%81%ED%83%80%EC%9E%85-%EC%96%B8%EC%96%B4-vs-%EB%8F%99%EC%A0%81%ED%83%80%EC%9E%85-%EC%96%B8%EC%96%B4
https://medium.com/@vishnupriya_web/what-is-typescript-faa0890b2baf
https://medium.com/@wonjong_oh/typescript-1-%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80-f4b02f54009c
https://velog.io/@denmark-banana/TypeScript-%ED%81%B4%EB%9E%98%EC%8A%A4%EC%99%80-%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4#1-%EA%B0%9D%EC%B2%B4%EC%A7%80%ED%96%A5-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D%EA%B3%BC-%ED%81%B4%EB%9E%98%EC%8A%A4-%EA%B8%B0%EC%B4%88

profile
to be frontend engineer

0개의 댓글