Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발공부일지

TypeScript - 제네릭(generics), tuple, interface 본문

TypeScript

TypeScript - 제네릭(generics), tuple, interface

보람- 2024. 1. 5. 13:43

목차

1. typescript 작성하기(자료형)

2. 제네릭(Generics)

3. 배열선언방식과 tuple

4. interface


 

 

 

 

 

 

 

 

1. typescript 작성하기(자료형)

변수명 : 타입 = 초기값

let num: number = 20;
const str: string = "typescript";
const nan: number = NaN;
const infinity: number = Infinity;
const bool: boolean = true;
const nullValue: null = null;
const undefinedValue: undefined = undefined;

const obj: object = {};

 

// 함수의 경우 반환되는 타입까지 지정해줘야함, 반환되는값이 없다면 void
const fn = (a: number): void => {
  console.log(a);
};

const sum = (a: number, b: number): number => {
  return a + b;
};

 

// 어떤타입이던지 할당가능, 타입오류를 잡으려고 ts를 쓰는건데 any를 쓰지않는걸로
const any: any = "";
console.log(any.length);

// 어떤타입이던지 할당가능, 하지만 타입의 안전성을 보장 검증 조건이 필요함(any와 다름)
const unkown: unknown = "";
if (typeof unkown === "string") console.log(unkown.length);

 

 

 

 

 

2. 제네릭( Generics )

https://www.typescriptlang.org/docs/handbook/2/generics.html#handbook-content

// 배열안에는 제네릭 문법 <T> 타입을 지정해줘야함, | 으로 조건을 걸어줄수도있음
const arr1: Array<number> = [1, 2];
const arr2: Array<number | string> = [1, "2"];

 

 

 

 

 

3. 배열선언방식과 tuple

https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types

// 문자열 타입의 배열
const strArr: string[] = ["1", "2", "3"];
const numArr: number[] = [1, 2, 3];

// 튜플 : 여러가지 데이터 타입을 가질수있는데 순서대로 정의해서 사용해야함
const tuple: [string, number, object] = ["hi", 2, {}];

 

 

 

 

 

4. interface

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#interfaces

 

interface IBlock {
  id: number;
  title: string;
  content: string;
  date: number;
  like: number;
  hit?: number;
}

// implements: 객체 구조형태만 상속받아 사용
class BlockClass implements IBlock {
  id: number = 1;
  title: string = "";
  content: string = "";
  date: number = 1;
  like: number = 1;
}

 

 

 

 

'TypeScript' 카테고리의 다른 글

Typescript - 2) more on design patterns with TS  (0) 2024.01.11
Typescript - design patterns with TS ①  (0) 2024.01.11
TypeScript - 전략패턴(Strategy Pattern)  (0) 2024.01.05
TypeScript  (0) 2024.01.04