GithubHelp home page GithubHelp logo

typescript-study's Introduction

Typescript-Study

타입스크립트 강의를 보고 기록하는 레포지토리입니다. (땅콩코딩) (벨로퍼트)

Typescript란?

js에 타입을 부여한 언어, js의 모든 기능 포함하고있으며 js에 포함되지 않은 새로운 기능도 있다. 변수 값에 데이터 타입을 지정 하는 특징을 가지고 있다.

let a: number = 1;

타입 추론(Type Inference)

Typescript에서는 타입 표기가 없는 경우 변수에 할당된 값을 보고 타입을 유추해낼 수 있다.

let a = 1;    //숫자 1을 할당해 a는 number로 추론
a = "hello";  //a의 타입이 number이기 때문에 오류 발생

타입 명시

변수를 선언할 떄, 변수 값의 타입을 명시해 변수 값의 데이터 타입을 지정해준다.

let a: number = 1;  //변수 뒤에 타입을 지정

//함수
function add(a:number, b:number): number {  //매개변수, 파라미터의 타입을 지정하고 함수리턴값에도 타입을 지정해준다 (void로 지정시 return이 없음을 뜻함)
  return a - b
}

//객체 
function getStudentDetails(studentID: number): {
  studentID: number;
  studentName: string;
  age: number;
  gender: string;
  subject: string;
}
//이런식으로 계속 지정하게되면 코드의 가독성이 떨어진다.

인터페이스(Interface)

코드를 효율적으로 쓸 수 있다.

interface Student {
  studentID: number;
  studentName: string;
  age: number;                                
  gender: string; 
  subject: string;
}

function getStudentDetails(studentID: number): Student{
  return {
    studentID: 12345,
    studentName: "Jenny",
    age: 18,
    gender: "femail",
    subject: "javascript",
  }
}

리턴해주는 값은 Student타입의 형식과 같아야한다.

선택적 프로퍼티

있어도 되고 없어도 되는 프로퍼티

interface Student {
  ...
  age?: number; //변수 앞에 ?를 붙혀준다.                               
}

메소드

객체 내에서 생성된 함수이다.

interface Student {
  ...
  //두 가지 방식이 있음
  addComment (comment: string): string;
  addComment?: (comment: string) => string;
}

readonly

읽을 수만 있게 하는 속성이다.

interface Student {
  readonly studentID: number;
  studentName: string;
  age: number;                                
  gender: string; 
  subject: string;
}

열거형(Enum)

이름이 있는 상수들의 집합을 정의할 수 있다.
의도를 문서화하거나 구분된느 집합을 더 쉽게 만들 수 있다.

enum GenderType {
  Male = "male",  //초기화 하지 않는다면 숫자 열거형으로 사용 0부터 순서대로 주어진다.
  Female = "female"
}

interface Student {
  ...                               
  gender: GenderType; 
}

리터럴 타입

Enum을 심플하게 사용할 수 있다.

interface Student { 
  ...                             
  gender: "male" | "female"; 
}

any 타입

아무런 타입이나 할당 가능
*정보를 명확히 명시해야하는 ts에서는 any타입은 가급적 사용하지 않는게 좋다.

let someValue: any = 5;
someValue = "string";

유니언 타입

OR연산자 같이 A이거나 B이다 라는 의미이다.

let price: number | string;
price = "hello";
price = 1;
price = true; // number 또는 string 타입이 아니므로 요류 발생

Type Aliases

2개 이상의 타입을 하나의 타입으로 묶고 싶을때 사용한다.

type StrOrNum = number | string;

Generics

함수, 클래스, interface, type alias 를 사용하게 될 때 여러 종류의 타입에 대하여 호환을 맞춰야 하는 상황에서 사용하는 문법이다.

만약 함수에서 return값이 어떤 타입이 올지 모를때 any라는 타입을 쓴다면 무엇이 값으로 오는지 예측 할 수 없게된다.
이런상황에서 Generics를 사용한다면 파라미터로 다양한 타입을 넣을 수도 있고 타입 지원을 지켜낼 수 있게된다.
//함수
function merge<A, B>(a: A, b: B): A & B {
  return {
    ...a,
    ...b
  };
}

const merged = merge({ foo: 1 }, { bar: 1 });

//인터페이스
interface Items<T> {
  list: T[];
}

const items: Items<string> = {
  list: ['a', 'b', 'c']
};

//type
type Items<T> = {
  list: T[];
};

const items: Items<string> = {
  list: ['a', 'b', 'c']
};

typescript-study's People

Contributors

seohyeon1578 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.