기록하는 타입스크립트 - 제너릭

FeelingXD·2022년 11월 23일
0
post-thumbnail

제너릭 !

타 컴파일 언어 (JAVA, C#)을 사용해봣더라면 익숙한 문법이다. 자바스크립트는 형태에대해서 엄격하지않아서 지원하지않지만 타입스크립트에서는 제너릭 문법을 지원한다.

const identify =<T>(input:T):T => input
console.log(typeof identify(1)) // => number
console.log(typeof identify('hello')) => string
console.log(typeof identify(true)) => boolean

위의 코드는 들어온 매개변수를 리턴해주는 함수이다.

❔ - 이렇게쓰면 Any 를 써도 되지않을까요 🙄

물론 Any를 사용해도 위와같은 함수는 Any로도 가능하다.

const anytype=(input:any)=>typeof input
console.log(anytype(1)); // number

하지만 특정 함수의프로퍼티를 사용하거나할때 문제가 생길수있다.
예를들어 String ,Array 타입처럼 길이를 나타내는 length의 프로퍼티를 number, boolean 등의 타입은 가지고있지않는다.

const anytypelength=(input:any)=>input.length
anytype(1) // undefined

any타입은 작성단계에서 타입검사를 하지않기때문에 사용을 지양해야한다.

profile
tistory로 이사갑니다. :) https://feelingxd.tistory.com/

0개의 댓글