Typescript 총정리

kyuu·2023년 4월 16일
0

타입스크립트 강의 정리
Joy of Code

함수 정의 Typescript

function returnString(name : string) : string {
  return name + "string";
}

Array Types

  • 배열 타입 정의를 위한 2가지 방법이 있음.
  • generic Array<Type> 문법이나,
  • Type[] 문법이 있음
const foo: Array<string> = ['foo1', 'foo2', 'foo3']

const foo: string[] = ['foo1', 'foo2', 'foo3']

Function Types

  • input과 output에 대한 타입 정의가 필요함
function addArray(target: string[], name: string): string[] {
  return target.push(name);
}

const addArray = (target: string[], name: string): string[] => {
  return target.push(name);
}
  • optional ?operator
function logFunc(info: string, code?: string){
  console.log({info, code})
}

Object Types

  • infered type & explicit type
const inferedEx = {
  name: 'meme'
}

const explicitEx: {name: string} = {
  name: 'meme'
}
  • optional
const optionalEx: {id?: string, name: string} = {
  name: 'meme'
} // 'id' is optional

Type Aliases

  • 타입을 별도의 변수로 정의할 수 있음
type Person = {id: number; name: string; mbti: string}

const person_foo: Person[] = [
  {
    id: 1,
    name: 'meme',
    mbti: 'INFJ
  }

]
  • 자바스크립트에선 함수도 특별한 객체에 불과하기 때문에, 함수 자체를 타입으로 정의할 수 있음
type LogPerson = (name: string) => void

// named function expression
const logMemeIns : LogPerson = function logMeme(name) {
  console.log(name);
}

// anonymous function expression
const logMeme: LogPerson = function(name) {
  console.log(name);
}

// anonymous arrow function expression
const logMeme: LogPerson = (name) => {
  console.log(name);
}

Interfaces

  • Interface는 Type Aliases의 다른 방식임

  • Interface를 사용함에 있어, 주의해야 할 점은 이미 시스템에 의해 정의된(eg, Window) 타입의 경우 사용하면 예상치 못한 결과를 얻을 수 있음.

interface Person {
  id: number;
  name: string;
  description?: string;
  callback(): void
}

const personMeme: Person = {
  id: 1,
  name: 'Meme',
  callback() {
    console.log('My name is meme');
  }

Type Aliases or Interfaces?

  • Interface는 공식적으로 객체의 타입을 명시하고 싶을 때, Type Aliases는 휴리스틱하게 작업하고 싶을 때 사용.
  • 정해진 것은 없으니, 마음대로 하면 됨.

    For the most part, you can choose based on personal preference, and TypeScript will tell you if it needs something to be the other kind of declaration. If you would like a heuristic, use interface until you need to use features from type. - TypeScript Handbook

Interface extends

  • extends keyword로 정의된 타입을 확장할 수 있음. (Typescript &와 같음)
interface Person {
  id: number;
  name: string;
};

interface Human extends Person {
  race: 'white';
}

const John: Human = { // satisfies
  id: 1,
  name: John,
  race: 'white
}

Union Types

function logPersons(names: string[] | string) {
  console.log(names);
}

Discriminated Unions

profile
!..!

0개의 댓글