jongviet

March 6, 2022 - typescript 본문

javascript & typescript

March 6, 2022 - typescript

jongviet 2022. 3. 6. 20:40

*3월6일

 

union type
type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

 

Generic
type StringArray = Array<string>;
type NumberArray = Array<number>;
type ObjectWithNameArray = Array<{ name: string }>;
 
Tuple: 요소 타입과 개수가 고정된 배열
const tuple: [string, number];
tuple = [“hi”, 1000];

 

Enum
enum Color {Red = 1, Green, Blue}
 
function a(): void {
    return nothing
}
 

 

Type Assertions
 
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length; // 믿고 따라와 느낌
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);

 

 

readOnly properties: 최초 할당만 유효

 

interface Point {
    readonly x: number;
    readonly y: number;
}
 

 

함수타입정의
 
interface SearchFunc {
    (source: string, subString: string): boolean;
}
 
let mySearch: SearchFunc; // 선언 후
mySearch = function(source: string, subString: string) { // 할당
    let result = source.search(subString);
    return result > -1;
}
 
인터페이스확장
 
interface Shape {
    color: string;
}

 

interface Square extends Shape {
    sideLength: number;
}
 
선택적 변수 or 기본값
function buildName(firstName: string, lastName?: string) {
    // ...
}
 
function buildName(firstName: string, lastName = "Smith") {
    // ...

 

}
 
rest params
 
function buildName(firstName: string, ...restOfName: string[]) {
    return firstName + " " + restOfName.join(" ");
}

 

let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie"); // employeeName : "Joseph Samuel Lucas MacKinzie" 

 

 

문자형 & 숫자형 리터럴
type Easing = "ease-in" | "ease-out" | "ease-in-out";
 
interface Bird {
  fly(): void;
  layEggs(): void;
}

 

declare function getSmallPet(): Fish | Bird;

 

partial 교차타입
 
interface Product {
    id: string;
    name: string;
}
 
interface PartialProduct {
    id?: string;
    name?: string;
}
 
const product1: Partial<Product> // Product를 PartialProduct 형태로 가지는 것~ 즉, 모두 optional로 만들어버림.
 
pick && omit
 
interface Product {
  id: number;
  name: string;
  price: number;
  brand: string;
  stock: number;
}

 

type essProduct = Pick<Product, "id" | "name”>; // 인터페이스 중 선택한 타입만 받는 형태
type essProduct = Omit<Product, "stock" | "brand" | "price”>; // 반대로 인터페이스 중 선택한 타입만 빼는 형태
 

 

논리연산자 처리

const test = (a: string, b: string) => {   
  return a && b; // a가 있으면 b 리턴, a가 없으면 리턴 없음
  return a || b; // a 있으면 a, a 없으면 b
};
const result = test("11", "마바사");

 

const status = {
   // stockBar : "22"
}
const test = status.stockBar ?? "정보없음";   // ‘??’ 앞이 없을 시 뒤 노출

 

console.log(test); // 정보없음
Comments