[web개발][javascript] TypeScript 기본 문법 정리

1. 기본 TS 타입 선언Permalink

문자열Permalink

 

let str: string = 'hello';

숫자Permalink

 

let num: number = 100;

배열Permalink

 

let arr: Array<number> = [10 , 20, 30];
let arr2: number[] = [10, 20, 30];
let arr3: Array<string> = ["lion", "tiger"];
let arr4: [string, number] = ["sejong", 182];

객체Permalink

 

let obj: object = { name: "yeom", age: 29 };
let person: { name: string, age: number };

BooleanPermalink

 

let isAvaliable: boolean = true;

2. 함수 선언Permalink

 

parameter와 return 값에 대해 타입 선언을 할 수 있다.

function sum(a: number, b: number): number {
  return a + b;
}

optional parameter일 경우 ? 를 사용한다.

function log(time: string, result?: string, option?: string) {
	console.log(time, result, option);
}

log("2021-10-04", "success");

3. 인터페이스(interface)Permalink

 

interface는 자주 사용하는 타입들을 object 형태의 묶음으로 정의해 새로운 타입을 만들어 사용하는 기능이다.

interface 선언Permalink

 

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

변수 활용Permalink

 

const yeom: User = { age: 30, name: 'kyeorae'}

함수 인자로의 활용Permalink

 

function getUser(user: User) {
  console.log(user);
}

getUser({ age: 10, name: 'hayoon'});

함수 구조 활용Permalink

 

interface Sum {
  (a: number, b: number): number;
}

let sumFunc: Sum: 
sumFunc = function(a: number, b: number): number {
  return a + b;
}

배열 활용Permalink

 

interface StringArray {
  [index: number]: string;
}

let arr: StringArray = ['a', 'b', c];

객체 활용Permalink

 

interface StringRegexObject {
  [key: string]: RegExp;
}

const obj: StringRegexObject {
  cssFile: /\.css$/,
  jsFile: /\.js$/
}

Interface 확장Permalink

 

extends 키워드를 사용한다

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

interface Developer extends Person {
  skill: string;
}

const juniorDeveloper = {
  name: 'yeom',
  age: 29,
  skill: 'sleep'
}

4. 타입 별칭(type aliases)Permalink

 

type 키워드는 interface와는 다르게 새로운 타입을 생성하는 것이 아닌 별칭을 부여하는 것이다. extends 키워드는 사용할 수 없다.

타입 별칭 선언 및 활용Permalink

 

type MyString = string;
const str: MyString = 'I love you';

type Todo = { 
  id: string;
  title: string;
  done: boolean;
};

function getTodo(todo: Todo) {
  console.log(todo);
}

5. 연산자(Operator)Permalink

Union TypePermalink

 

한 가지 이상의 type을 선언하고자 할 때 사용할 수 있다. | 기호를 사용한다

function logMessage(value: string | number) {	// 함수 호출시 value 인자의 타입에는 string 또는 number
  if(typeof value === 'string') {
    value.toString();
  } else if(typeof value === 'number') {
    value.toLocaleString();
  } else {
    throw new TypeError('value must be string or number');
  }
}

logMessage('hello');
logMessage(100);

Intersection TypePermalink

 

합집합과 같은 개념. 함수 호출의 경우. 함수 인자에 명시한 type을 모두 제공해야 한다. & 키워드를 사용한다.

interface Zoo {
    name: string;
    location: string;
    price: number;
}

interface Animal {
    name: string;
    count: number;
}

// Union: Zoo나 Animal에 해당하는 인자를 제공해야 한다
askZookeeper({ name: 'tiger', count: 3});

// Intersection: Zoo나 Animal에 해당하는 인자를 줘야한다(합집합 같은 개념)
askZookeeper2({ name: '어린이대공원', location: '서울시 광진구', price: 10000, count: 10000 });

6. EnumPermalink

 

enum 키워드를 사용하면 일종의 default 값을 선언할 수 있다.

숫자형 enumPermalink

 

자동으로 0에서 1씩 증가하는 값을 부여

enum Shoes {
  Nike,				// 0
  Adidas,			// 1
  NewBalance	// 2
}

const myShoes = Shoes.Nike;	// 0

문자형 enumPermalink

 

enum Player {
  Koke = '코케',
  Saul = '사울'
}

const player = Player.Koke;	// 코케

7. ClassPermalink

Class에서의 타입 선언Permalink

 

class Tiger {
  // constructor 위에 선언
  private name: string;
  public age: number;
  readonly log: string;
  
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

8. 제네릭(generics)Permalink

 

제네릭을 활용하면 인자를 넘겨 호출하는 시점에 타입을 결정할 수 있다. 제네릭을 활용하면 동일한 기능을 하는 함수를 일일이 만들 필요가 없으며, 타입 추론에 있어서 강점을 가진다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

제네릭 선언Permalink

 

<T>와 같이 타입을 선언한다. 알파벳은 통상 T로 정해져 있다.

function logText<T>(text: T): T {
  consol.log(text);
  return text;
}

logText<string>('Hello My World!');

interface에 제네릭 선언Permalink

 

interface Dropdown<T> {
	value: T;
  selected: boolean;
}

const obj: Dropdown<string> = { value: 'hamburger', selected: true };

제네릭 타입 제한Permalink

1. 배열 힌트Permalink

 

function logTextLength<T>(text: T[]): T[] {
    console.log(text.length);
    text.forEach(text => {
        console.log(text);
    });
    return text;
}

logTextLength<string>(['hi', 'hello']);

2. 정의된 타입 이용(extends)Permalink

 

interface LengthType {
    length: number;
}

function logTextLen<T extends LengthType>(text: T): T {
    console.log(text.length);
    return text;
}

logTextLen('abc');
// logTextLen(100); // 숫자에 length property가 없으므로 에러
logTextLen({ length: 100 });

3. keyofPermalink

 

interface에 정의된 key 값만을 허용

interface ShoppingItem {
    name: string;
    price: number;
    stock: number;
}

function getShoppingItemOption<T extends keyof ShoppingItem>(itemOption: T): T {
    return itemOption;
}

// 'name', 'price', 'stock'만 인자로 가능
getShoppingItemOption('price');

9. 타입 추론(type inference)Permalink

기본 변수 타입 추론Permalink

 

// string으로 추론
let a = 'abc';	

// a: number로 추론
// b: string으로 추론
// return value는 string으로 추론
function getValue(a = 10) {
  let b = 'hello';
  return a + b;
}

interface 추론Permalink

 

// interface 1개
interface Dropdown<T> {
    value: T;
    title: string;
}
const shoppingItem: Dropdown<number> = {
    value: 10000,
    title: 'shoe'
}

// interface 2개
interface Dropdown2<T> {
    value: T;
    title: string;
}
interface DetailedDropdown<K> extends Dropdown2<K> {
    tag: K;
    desc: string;    
}
const detailed: DetailedDropdown<string> = {
    value: '10000',
    title: 'shoe',
    tag: '10000',
    desc: 'description'
}

10. 타입 단언(type assertion)Permalink

 

as 키워드를 사용해 타입을 정함으로써 typescript에게 타입을 알려줄 수 있다. 주로 DOM API를 조작할 때 사용한다고 한다.

타입 단언 예제Permalink

 

// div가 있는지 장담할 수 없음, HTMLDivElement | null
// 따라써 typescript에게 타입 단언해 타입을 알려 줄 수 있다.
const div = document.querySelector('div') as HTMLDivElement;
div.innerText = 'test';

11. 타입 가드(type guard)Permalink

 

Union Type을 사용하는 경우 공통된 속성만 접근이 되므로, 로직상 공통되지 않은 속성에 접근하고자 할 때 불편함이 따를 수 있다. 타입 단언으로 공통되지 않은 속성에 접근하고자 하는 방법이 있지만, 코드가 지저분해지므로 타입 가드 방법을 사용한다.

타입 가드 예제Permalink

 

function isDeveloper(target: Developer | Humanoid): target is Developer {
    return (target as Developer).skill !== undefined;
}

if(isDeveloper(tom)) {
    console.log(tom.name);
    console.log(tom.skill);
} else {
    console.log(tom.name);
    console.log(tom.age)
}

12. 타입 호환(type compatibility)Permalink

 

typescript에서는 더 큰 타입 구조를 갖는 변수에 작은 타입 구조를 갖는 변수를 할당할 수 있다. 예제를 보자.

타입 호환 예제Permalink

 

let add = function(a: number) {
    // ...
}
let sum = function(a: number, b: number) {
    // ...
}
// 아래는 에러가 난다
// add = sum;

// 에러가 나지 않는다. sum의 구조가 더 크다고 볼 수 있으므로.
sum = add;

 

 

[출처] https://yeomkyeorae.github.io/typesciprt/basic_typescript/#1-%EA%B8%B0%EB%B3%B8-ts-%ED%83%80%EC%9E%85-%EC%84%A0%EC%96%B8

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
27 [wordpress, 워드프레스] 워드프레스로 쉽게 랜딩 페이지 만들기 (feat. 엘리멘터, GeneratePress, Divi) file 졸리운_곰 2024.12.20 545
26 [wordpress, 워드프레스] WordPress 페이지또는 글에 별도 CSS와 JavaScript 추가하기 file 졸리운_곰 2024.12.19 354
25 [wordpress 플러그인] 코스모스팜. 회원관리 1.메뉴에 로그인 넣기 file 졸리운_곰 2024.08.25 513
24 [wordpress 플러그인] WP-Members로 회원제 사이트 만들기 file 졸리운_곰 2024.08.25 749
23 [php worldpress] 워드프레스 새 서버 이전시 페이지 안나오는 문제 : How to Rewrite URLs with mod_rewrite for Apache on Ubuntu 20.04 file 졸리운_곰 2024.08.07 774
22 [php worldpress] PHP query to SQL server database (wordpress) 졸리운_곰 2024.07.28 503
21 [php worldpress] [위 에]wordpress 사용자 암호 화 원리 및 알고리즘 분석 졸리운_곰 2022.04.11 377
20 [wordpress] WPForms 워드프레스 폼빌더 사용법 file 졸리운_곰 2021.04.25 1715
19 [wordpress][워드프레스] 워드프레스에서 wpdb를 사용한 CRUD 작업 예 졸리운_곰 2021.04.15 356
18 워드프레스에서 wpdb를 사용한 CRUD 작업 예 졸리운_곰 2021.01.12 459
17 워드프레스 – CRUD file 졸리운_곰 2021.01.02 501
16 워드프레스 데이터베이스 들여다보기. file 졸리운_곰 2020.08.04 673
15 워드프레스 플러그인과 테마 비교 - 사이트별 플러그인 만들기 졸리운_곰 2020.04.21 501
14 워드프레스에서 js 스크립트 파일과 스타일시트를 올바르게 로드하는 방법 졸리운_곰 2020.04.21 735
13 워드프레스 플러그인 만들기 file 졸리운_곰 2020.04.21 500
12 워드프레스 숏코드: 완벽 가이드 file 졸리운_곰 2020.04.21 513
11 워드프레스 페이지 분석 file 졸리운_곰 2019.11.19 515
10 내가 본 워드프레스 핵심 구조 및 기능 (Wordpress Architecture and Function) file 졸리운_곰 2019.11.19 452
9 Embedding three.js in WordPress 워드프레스에서 three.js 사용 졸리운_곰 2019.11.08 517
8 How to Super Charge your WordPress with Microservices 워드프레스 마이크로서비스 file 졸리운_곰 2019.11.03 373
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED