본문 바로가기

IT/typescript34

[typescript] in 개념TypeScript에서 in 연산자는 객체에 특정 속성이 존재하는지 확인하는 데 사용됩니다. 이는 자바스크립트의 in 연산자와 동일한 방식으로 작동하며, 객체의 프로토타입 체인에서도 속성을 확인합니다.예시in 연산자의 사용을 이해하기 위해 간단한 예제를 살펴보겠습니다.interface Person { name: string; age: number;}const person: Person = { name: "John", age: 30};if ('name' in person) { console.log("Name exists in person");}if ('address' in person) { console.log("Address exists in person");} els.. 2024. 6. 12.
[typescript] as const https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions 를 읽고 정리한 글입니다. as const를 선언하면, - string에서 'hello'로 추론됨 (아래 코드 확인) - obejct는 readonly로 설정 - array는 readonly tuples로 변경 let x = ‘hello’ // string으로 추론let x = ‘hello’ as const // hello으로 추론let y = [10, 20] // number[]으로 추론let y = [10, 20] as const // readonly [10, 20]으로 추론let z = { text: 'hello' } // { t.. 2024. 6. 3.
[clean code] 놓치기 쉬운 것들 Use explanatory variables // bad const address = "One Infinite Loop, Cupertino 95014"; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; saveCityZipCode( address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2] ); // good const address = "One Infinite Loop, Cupertino 95014"; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; const [_, city, zipCode] = address.. 2024. 4. 22.
[typescript] Union & Intersection 정리Union Type에서의 교집합, 합집합과 구조적 타입에서의 교집합, 합집합의 개념은 다르다.구조적 타이핑은 객체가 어떤 타입에 부합하는 최소한의 특징을 가지고 있다면, 그 타입에 해당하는 것으로 간주한다. Union Type여러 타입 중 하나를 가질 수 있다.  개념은 너무 쉬워서 넘어가고, 값을 넣을 때는 합친 타입 중 아무거나 넣으면 되고,사용할 때는 어떤 타입을 사용할 것인지 확인 후 사용. 즉, Narrowing해서 사용 단, 사용할 로직이 어느 타입이든 상관없다면 Narrowing 할 필요는 없음function printId(id: number | string) { if (typeof id === 'number') { console.log(`${id} is number`).. 2024. 3. 17.
[Typescript] Type Assertion 언제 사용하나 Typescript가 알 수 없는 type이거나 추론한것보다 개발자가 더 정확한 타입을 알고 있을 때 타입을 강제할 수 있다. 예) getElementById에서는 HTMLElemnt를 리턴하는데, 개발자는 canvas를 가져올것을 알기에 HTMLCanvasElement 으로 강제시킨다. const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement; 특징 컴파일 때 사라지기에 런타임 때 영향을 받지 않는다. 그래서 강제한 타입이 틀리더라도 null이나 exception이 발생되지 않는다. 하지만 조심해야 한다. 경험사례로, string을 enum 타입으로 강제해서 사용했지만 런타임에서는 enum타입에 맞지 않아 u.. 2024. 3. 16.
[typescript] Array가 Record type에 호환이 된다고? 결론 맞다. 뿐만아니라 function, Map, Date, Boolean, String, class도 된다. Record Type type Record = { [P in K]: T; } 이유 key의 형태가 index signature로 되어 있기 떄문이다. [P in K] 가 array['0'] 를 받아줄 수 있기 때문이다. const a = [1, 2, 3, 4, 5] const b: Record = a console.log('a', a) // [1, 2, 3, 4, 5] console.log('b', b) // [1, 2, 3, 4, 5] console.log('isArray', Array.isArray(b)) // true 더 신기한 사실!! string 자체도 Record에 호환이 된다. 이유.. 2024. 3. 13.