TypeScript 12

타입 가드(Guards)

다음과 같이 value 타입을 매번 보장하기 위해 타입 단언을 여러 번 사용되기도 한다. function checkNumber(value: string | number, isNumber: boolean) { if (isNumber) { (value as number).toFixed(2); isNaN(value as number); } else { (value as string).split(""); (value as string).toUpperCase(); (value as string).length; } } 위 경우보다 타입 가드를 제공하면 추론 가능한 특정 범위안에서 타입을 보장할 수 있게 된다. 타입가드는 Name Is Type 형태의 타입 술부(Predicate)를 반환 타입으로 명시한 함수다. f..

TypeScript 2022.07.28

제네릭(Generics)

제네릭(Generics)의 사전적 정의 제네릭은 재사용성이 높은 컴포넌트를 만들 때 자주 활용되는 특징이 있다. 특히, 한가지 타입보다 여러 가지 타입에서 동작하는 컴포넌트를 생성하는데 사용된다. 일반적으로 함수를 만들어서 매개변수를 이용해 값을 반환하는 예시 function getText(text) { return text; } getText('hi'); // 'hi' getText(10); // 10 getText(true); // true 같은 함수이지만 제네릭을 통해 사용한다면? function getText(text: T): T { return text; } //위 함수는 제네릭 기본 문법이 적용되었다. 함수를 호출할 때 아래와 같이 함수 안에서 사용할 타입을 //넘겨줄 수 있다. getText..

TypeScript 2022.07.17

Record Type

Record Type이란? Record Type은 Record 형식으로 키가 Key이고 값이 Type인 객체 타입이다. Record Type 과 Index Signature TypeScript에서 인덱스 시그니처(Index Signature)는 대괄호로 객체에 접근하는 방법이다. Index Signature 방식 type foo = { [name: string]: number }; let user:foo = { 'a': 1, 'b': 2, 'c': 3, }; Record Type 방식 type foo = Record let user:foo = { 'a': 1, 'b': 2, 'c': 3, }; 두 가지 방식은 둘 다 비슷 해보이지만, 구문 관점에서는 Index Signature가 더 좋아보인다. name..

TypeScript 2022.07.16

TS에서 type과 interface의 차이점은?

타입스크립트에서 type도 타입이 지정이 가능하고, interface도 타입이 지정이 가능한데 그렇다면 두 개의 차이점이나 공통점은 무엇일까? 라는 궁금중이 생겼다. 기본 사용법 interface PeopleInterface { name: string; age: number; } const first: PeopleInterface = { name: 'abc', age: 123, }; type PeopleType = { name: string; age: number; }; const second: PeopleType = { name: ' abc', age: 123, }; 위에 코드처럼 interface도 type처럼 객체의 타입을 지정해줄 수 있는 또 다른 방법이다. 서로 다른 확장법 interface는 ..

TypeScript 2022.06.16

react에서 type 설정 하는 방법

1. IntrinsicElements['해당요소']를 설정해준다. 또는 Element만 작성해줘도 무방 let box: JSX.IntrinsicElements['div'] = hello; let box2: JSX.Element = hello; 2. 컴포넌트를 반환할 때도 마찬가지로 아래와 같이 작성하면 된다. function Component(): JSX.Element { return 컴포넌트입니다.; } 3. Props 지정, Props는 잘못 전달해서 에러가 잦기 때문에 타입지정을 잘해줘야 한다. function Component(props: { name: string }): JSX.Element { return {props.name}; } 4. useState타입은 자동으로 지정된다. 하지만 만약 ..

TypeScript 2022.05.13

interface 사용법

interface Student { name: string; } //Student name 속성을 복사해 붙여넣는다고 생각하면 좋다. 해당하는 타입 설정해놓은 값을 쓸 수 있다. interface IProps extends Student { age: number; } let student: Student = { name: 'yo' }; let teacher: IProps = { name: 'yo', age: 30 }; type 과 interface의 차이점은? interface는 중복 선언이 가능하다. 하지만 type은 불가능하다. 즉 합쳐진다. 하지만 type은 엄격해서 중복시 중복되었다고 에러메시지가 뜬다. interface는 외부 라이브러리가 interface를 많이 사용하는데, 타입이 불만족스러울..

TypeScript 2022.05.13

타입스크립트로 HTML 변경과 조작할 때 주의점들

const title = document.getElementById('title'); //HTML 조작시 narrowing 방법 5개 정도가 있다. if (title !== null) { title.innerHTML = 'hello'; } if (title instanceof Element) { //Element 요소의 타입이냐라는 뜻 title.innerHTML = 'instanceof'; } //const title = document.getElementById('title') as Element; //무조건 이걸로 Element로 바꿔서 가능. 비상시 사용. if (title?.innerHTML) { //title이 있냐 없냐를 간단히 요약한 문법, optional chaining title.inn..

TypeScript 2022.05.12

타입도 변수에 담아쓴다. type 키워드 써서 & readonly, Literal Types로 만드는 const 변수 유사품

1. type 키워드 & readonly //type alias type Animal = string | number | undefined; let animal: Animal = 123; type UserType = { name: string; age: number }; let user: UserType = { name: 'yohan', age: 30 }; //타입스크립트내에서는 readonly를 사용하면 수정이 불가하다. type Name = { readonly name: string }; const man: Name = { name: 'yo', }; type Age = string; type City = number; //union type으로 합치기 또한 가능하다 type Person = Name ..

TypeScript 2022.05.11

타입 확정하기 Narrowing & Assertion

1. Narrowing 타입이 아직 하나로 확정되지 않았을 경우 //타입이 어떤 타입인지에 대해 조건식으로 코드를 짜야한다. //타입이 아직 불확실하다면 Narrowing해줘야 한다. //주의점은 if문을 사용했으면 끝까지 써야 안전하다. else, else if문까지. //typeof 변수 //속성명 in 오브젝트자료 //인스턴스 instanceof 부모 function func(x: string | number) { if (typeof x === 'number') { return x + 1; } else { return x + '1'; } } func(123); function arrFunc(x: number | string): void { let arr: number[] = []; if (typeo..

TypeScript 2022.05.11

union type, any, unknown, 함수에 타입 지정하는 법 & void 타입

1. Union Types //1. Union Types //타입 2개 이상 합친 새로운 타입) let names: number | string = 123; let ages: number | string | boolean = true; names = 'name!'; ages = 30; //소괄호로 타입을 묶어준다. let arr: (number | string)[] = [1, 'string', 3]; let obj: { a: string | number } = { a: 123 }; 2. any Types && Unknown Types //any 타입 //어떤 타입이 들어와도 에러가 나지 않는다. 모든 자료형을 허용해줌. //하지만 타입스크립트 쓰는 의미가 없다. 타입실드 해제문법. let user: an..

TypeScript 2022.05.11
반응형