Type Aliases

type Point = {
	x: number;
  	y: number;
};

type ID = number | string;

url:https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases

Interface

interface Point {
  x: number;
  y: number;
}
// readonly -> 변경 불가능
interface Point {
  readonly x: number;
  y: number;
}

url:https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#readonly-and-const

Type vs Interface

// interface
interface Animal {
  name: string
}

interface Bear extends Animal {
  honey: boolean
}

const bear = getBear() 
bear.name
bear.honey

// type 
type Animal = {
  name: string
}

type Bear = Animal & { 
  honey: boolean 
}

const bear = getBear();
bear.name;
bear.honey;

void vs unknown vs never

void

void는 값을 반환하지 않는 함수의 반환 값을 나타냅니다. 함수에 return 문이 없거나 해당 return 문에서 명시적 값을 반환하지 않을 때 항상 유추되는 타입입니다.

// The inferred return type is void
function noop() {
return;
}

unknown

unknown타입은 모든 값을 나타냅니다. 이것은 any타입과 비슷하지만 any보다 unknown이 더 안전합니다. 이유는 unknown값으로 작업을 수행하는 것은 합법적이지 않기 때문입니다.

function hello(a: any) {
a.b(); // OK
}

// ❌
function hello2(a: unknown) {
a.b(); // 에러: Object is of type 'unknown'.
}

// ✅
function hello2(a:unknown) {
	if(typeof a === "number"){
    	let b = a + 1;
    }
  	if(typeof a === "string"){
    	let b = a.toUpperCase();
    }
}

never
일부 함수는 값을 반환하지 않습니다.
이는 함수가 예외를 throw하거나 프로그램 실행을 종료함을 의미합니다.

function fail(msg: string): never {
throw new Error(msg);
}

url: https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown

Call Signatures

프로퍼티로 호출 가능한 것을 설명하려면 객체 타입에 Call Signature을 작성할 수 있습니다.

type PizzaFunction = {
pizza: string;
(args: number): boolean;
};

function hello(fn: PizzaFunction) {
console.log(fn.pizza, fn(6));
}

url: https://www.typescriptlang.org/docs/handbook/2/functions.html#call-signatures

Function Overloads

동일한 이름에 매개 변수와 매개 변수 타입 또는 리턴 타입이 다른 여러 버전의 함수를 만드는 것을 말합니다. TypeScript에서는 오버로드 signatures을 작성하여 "다양한 방식으로 호출할 수 있는 함수"를 지정할 수 있습니다.

type Add={
(a:number,b:number):number;
(a:number,b:number,c:number):number;
}

const add:Add=(a,b,c?:number)=>{
return a+b;
}
add(1,2)
add(1,2,3)

Polymorphism (다형성)

다형성이란, 여러 타입을 받아들임으로써 여러 형태를 가지는 것을 의미합니다.

type SuperPrint={
(arr:T[]):T;
}

const superPrint:SuperPrint=(arr)=>{
return arr[0]
}

const a=superPrint([1,2,3])
const b=superPrint([true,false,true])
const c=superPrint(["a","b"])
const d=superPrint([1,2,"a","b",true])

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

Generics

제네릭은 C#이나 Java와 같은 언어에서 재사용 가능한 컴포넌트를 만들기 위해 사용하는 기법입니다. 단일 타입이 아닌 다양한 타입에서 작동할 수 있는 컴포넌트를 생성할 수 있습니다.
(구체적인 타입을 지정하지 않고 다양한 인수와 리턴 값에 대한 타입을 처리할 수 있다.)
타입스크립트에서 제네릭을 통해 인터페이스, 함수 등의 재사용성을 높일 수 있습니다.

function identity< Type >(arg: Type): Type {
return arg;
}

// 제네릭 화살표 함수 (tsx기준)
const identity=< Type extends {} >(arg: Type):Type => {
return arg;
}

let output = identity("myString"); // 첫 번째 방법
let output = identity("myString"); // 두 번째 방법
// 두 번째 방법은 type argument inference(타입 인수 유추)를 사용합니다. 즉, 컴파일러가 전달하는 인수 유형에 따라 자동으로 Type 값을 설정하기를 원합니다.

url:
https://www.typescriptlang.org/docs/handbook/2/generics.html

0개의 댓글