Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

효뚜르팝의 Dev log

Solving TypeScript Errors 본문

TIL

Solving TypeScript Errors

hyodduru 2024. 5. 21. 22:50
https://www.totaltypescript.com/tutorials/solving-typescript-errors 강의를 듣고 기록한 내용입니다. 

Fixing "Property Does Not Exist On Type" 

 

object를 dynamic하게 사용하고 싶을 때는 Record 타입을 사용하기 

const user: Record<Strong, number | string> = {
	name : "Matt",
 }; 
 
 user.age = 24;

 

Fixing "X is Possibly Null Or Undefiend" 

null이 아님을 보장하고 싶을 때는 ! 을 사용하기 

-> 런타임일 때는 null이기 때문에 에러를 유발할 수 있기 때문에 안전한 방식은 아님. 

const searchParams = new URLSearchParams(window.location.search);

const id = searchParams.get("id");

console.log(id!.toUpperCase());

 

아래와 같은 방식이 더 안전함.  (혹은 optional chaining) 

if(id) {
	consol.log(id.toUpperCase());
    }
if(!id) {
	throw new Error("Id not found");
    }
    
console.log(id.toUpperCase());

 

Fixing "Types Of Property Are Incompatible"

satisfies 타입을 활용할 수 있다. 

 

-> 타입 에러가 어디서 발생했는지 명확하지 않을 때에는 타입을 직접 지정해줌으로써 어디서 에러가 발생했는지 파악하기 

type RoutingConfig = {
	routes: {
    	path: string;
        component: string;
        }[];
 };   


const routingConfig = {
	routes: [
    	{
            path: "home",
            component: "HomeComponent",
         },
         {
            path: "about",
            component: 12, // 바로 타입 에러를 확인할 수 있음 
         },
       ]
      } satisfies RoutingConfig; 
      
const createRoutes = (config: RoutingConfig) => {}; 

createRoutes(routingConfig);

 

Fixing "X is Of Type Unknown" 

unknown : 어떤 것이든 될 수 있는 타입. but any와는 다름. any는 타입 체크를 하지만 unknown은 타입 체크를 하지 않음. 

 

type assertion을 사용할 수 있음. (error를 any라고 지정하기 보다는...) 

unknown 타입을 Error라고 강제하는 방식이기 때문에 별로 안전한 방식은 아님. 

const somethingDangerous = () => {
	if(Math.random() > 0.5){
    	throw new Error("Oh dear!");
        }
     };
     
     
 try {
 	somethingDangerous();
 } catch (error) {
 	console.log((error as Error).message);
  }

 

좀더 안전한 방식은 조건문에서 타입을 확인하는 것 

try {
	somethingDangerous();
} catch (error) {
	if(typeof error === "object" && error && "message" in error) {
    console.log(error.message);
     } else {
        throw error;
       }
   }

 

좀더 간단하고 안전한 방식 

// 이 방식 써먹어야겠다...!! 

try {
 somethingDangerout();
} catch (error) {
 if (error instanceof Error) {
     console.log(error.message);
   } else {
   	  throw error;
    }
 }

 

 

Fixing "Expression Can't Be Used To Index Type X"

index로 string 타입을 사용하고자 할 때, Record 타입을 활용할 수 있다. 

const productPrices: Record<string, number> = {
    Apple: 1.2, 
    Banana: 0.5, 
    Orange: 0.8, 
 };
 
 const getPrices = (productName: string) => {
 	return productPrices[productName];
 };

 

혹은 적절한 string이 들어가도록 타입을 보장하고 싶은 경우 productName의 타입을 지정해줄 수 있음 

 

 const getPrices = (productName: 'Orange' | 'Apple' | 'Banana') => {
 	return productPrices[productName];
 };

 

혹은 keyof typeof을 활용해서 중복된 타입을 적지 않아도 된다. 

 

const getPrice = (productName: keyof typeof productPrices) => {
	return productPrices[productName];
  };

 

keyof typeof + type assertion도 가능하다. 

const getPrice = (productName: keyof typeof productPrices) => {
	const index = productName as keyof typeof productPrices; 

	return productPrices[index];
  };

 

 

Fixing "Fixing Conversion Of Type X Maybe A Mistake"

 

Fixing "Cannot Redeclare Block-Scoped Variable"

tsconfic에서 moduleDetection : "force" 추가 시, 모든 프로젝트 코드가 module임을 알려주어 위와 같은 에러가 나타나지 않을 수 있음.

 

Fixing "Could Not Find A Declaration File"

Declaration File  :  자바스크립트에 대해서 설명하는 a.d.ts file