타입스크립트 function_1

nevermind·2022년 10월 22일
0

typescript

목록 보기
4/12

readonly(읽기전용)

  • 의도치 않은 값의 변경으로 인해 생기는 오류 방지할 수 있다
    - 읽기만 가능하다
    - .push(), .pop() 등 안된다(변경 x)
    - map, filter 함수로 돌려줘서 조회는 가능
type A = {
  readonly barA: string
};

const x: A = {barA: 'baz'}; 
x.barA = 'lalala'; // ⛔️ 변경 불가

any

  • Typescript의 모든 보호장치를 비활성화시킨다(string, number, boolean 등 상관없게 만들어준다)
const a : any[] = [1,2,3,4]
const b : any = true
a + b //허용됨

unknown

  • 알 수 없다 모른다라는 의미
  • any타입과 동일하게 모든 값을 허용하지만 할당된 값이 어떤 타입인지 모르기에 함부로 프로퍼티나 연산을 할 수 없다
  • unknown. 타입이라 어떤 값이든 올 수 있다 그러기에 엄격히 검사해라라는 의미이기도 함
  • 아래와 같이 쓰면 문제없이 동작
let valueNum: unknown = 10;
let valueStr: unknown = "unknown";

if (typeof valueNum === "number") {
  console.log(valueNum.length);
}

if (typeof valueStr === "string") {
  console.log(valueStr.length);
}

void

  • return 할 자료가 없는 함수의 타입일 때 사용
function a(x :number) :void { 
  return x * 2 //여기서 에러남 
} 

never

  • return하지 않고 에러를 발생시킬 때 사용
function hello () : never {
  	// return 'hi' <- 에러
	throw new Error('~~') 
}

call signature

  • call signatures란 함수 이름 위에 커서를 올렸을 때 뜨는 파라미터 타입 정보와 리턴 타입 정보
  • call signature로 개발자가 직접 타입을 만들 수 있고, 함수가 어떻게 동작하는지 서술해둘 수 있음
type Add = (a:number, b:number) => number;
const add:Add = (a,b) => a + b
//const add:Add = (a,b) => {a + b} <- void가 됨

overloading

  • Function(=Method) Overloading은 직접 작성하기보다 외부 라이브러리에 자주 보이는 형태로, 하나의 함수가 복수의 Call Signature를 가질 때 발생한다

  • TypeScript에서는 오버로드 signatures을 작성하여 "다양한 방식으로 호출할 수 있는 함수"를 지정할 수 있다

  • 매개변수의 데이터 타입이 다른 경우 예외 처리

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

const add: Add = (a, b) => {
if (typeof b === "string") return a;
return a + b;
}
  • 매개변수의 수가 다른 경우 예외 처리
type Add2 = {
(a: number, b: number): number,
(a: number, b: number, c: number): number
}

const add2: Add2 = (a, b, c?: number) => {
if (c) return a + b + c;
return a + b;
}

위와 같은 함수는 거의 없지만 외부 라이브러리에서 활용될 수 있다

//Next.js 경우
router.push("/home");

router.push({
path: "/home",
state: 1
});

예를 들어, Next.js의 라우터 push가 대충 두 가지 방법으로 페이지를 이동한다고 할 때,

type Config = {
path: string,
state: number
}

type Push = {
(config: Config): void,
(config: string): void
}

const push: Push = (config) => {
if (typeof config === "string") console.log(config);
else console.log(config.path);
}

패키지나 라이브러리는 위와 같이 두 가지 경우의 Overloading으로 디자인되어 있을 것이다


출처 : https://velog.io/@ysong0504
https://yamoo9.gitbook.io/typescript/types/any
https://developer-talk.tistory.com/198
https://nomadcoders.co/typescript-for-beginners

profile
winwin

0개의 댓글