React (typescript) string 타입으로 객체에 접근하기

Southbig·2022년 8월 18일
0

string 타입으로 객체에 접근 에러

typescript err
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'

string 형식은 객체에 접근 할 수 없다는 뜻이다

무슨 뜻이냐 하면
string 형식은 object의 key값으로 사용할 수 없다고 한다

이유

typescript의 가장 큰 특징은 특정한 곳에 특정 타입만 허용하는 것

위의 에러는 string literal 타입만 허용되는 곳에 string 타입을 사용했기 때문

TypeScript는 기본적으로 객체의 프로퍼티를 읽을 때, string타입의 key 사용을 허용하지 않는다
반드시 string literal 타입의 key로 접근하거나 객체의 타입 정의 시, index signiture를 선언해주어야한다

string과 string literal은 무슨차이지 ?

const a = "Hello World"
// 👉 컴파일러는 이 변수를 string이 아닌 조금 더 좁은 타입으로 선언한 것으로 추론한다.(Literal Narrowing)
// 👉 a의 타입은 string 타입보다 훨씬 구체적인 "Hello World" 타입이다.

let b = "Hello World"        
// 👉 b변수는 let으로 선언되어 재할당될 수 있을 경우 어떤 문자열이든 넣을 수 있으며 그 경우의 수가 무한대
// 👉 그렇기 때문에 컴파일러는 이 변수를 string타입으로 추론한다.

const c: string = "Hello World"
//c 변수는 명시적으로 string 으로 선언했으므로 string 타입이다.
const obj = {
   foo: "hello"   
   }

let propertyName = "foo"  //propertyName는 string 타입(let) 

console.log(obj[propertyName])
// 🕹 컴파일 에러!
//에러가 발생한 이유는 string literal 타입만 허용되는 곳(객체의 key)에 string 타입을 사용했기 때문
  foo: "hello",
}

const propertyName = "foo"

console.log(obj[propertyName]) // ok!
console.log(obj["foo"]) // ok!
// 👉 정상 컴파일
// 👉 "foo"와 propertyName 모두 string literal type

String Literal의 유용함

String Literal타입은 열거형 타입처럼 사용할 때 매우 유용하다
마우스 이벤트가 있다고 가정하고, 이벤트 종류는 정해져있지만 이벤트 이름을 String 타입으로 받을 때는 오타 혹은 유효하지 않은 이벤트 이름으로 인해 발생하는 런타임 에러를 사전에 방지 할 수 없다

<function handleEvent(event:string) {} // 이벤트 이름을 string 타입으로 받는다면
handleEvent("clock") 
handleEvent("click")  //compile error : 오타. 컴파일 타임에 발견할 수 없다.
handleEvent("hover")  //compile error : 유효하지 않은 이벤트 이름. 컴파일 타임에 발견할 수 없다

반면, string literal 타입 조합만을 허용하도록 하면 사전에 오타 혹은 여러가지 에러를 방지할 수 있다

type EventType = "mouseout" | "mouseover" | "click" //string literal 타입들의 조합
function handleEvent(event:EventType) {}  //string literal 타입들의 조합을 이벤트(매개변수)의 타입으로 선언한다.
handleEvent("click")
handleEvent("hover") //compile error : EventType이라는 타입에 해당 string literal이 정의되지 않았기 떄문

String 키를 이용한 객체 접근 방법

index signature를 선언

객체의 프로퍼티를 읽을 때 key값에 string literal 타입이 아닌 string 타입이 들어가도 컴파일이 가능하다

interface ObjType {
	[key: string]: string;
}
type ObjType = {
	[anyKeyword: string]: string;
}

string 타입으로 된 index signature를 선언함으로서 string, literal type을 사용하여 object에 접근할 수 있게 된다

string 타입으로 객체에 접근하려면 index signautre 사용


참고 사이트

사이트1

사이트2

사이트3

profile
즐겁게 살자

0개의 댓글