본문 바로가기
IT/typescript

[Typescript] Complier Options - suppressImplicitAnyIndexErrors

by 내일은교양왕 2024. 3. 12.

개념

object에 있는 값을 indexing 하는 방식으로 값을 가져올 때 2가지 상황에 대해서 암묵적인 any로 추론되는데, 이 에러 경고를 무시하는 옵션

 

첫번째 상황

object type에서 없는 키 index signature에 넣었을 때

 

두번째 상황

keyof typeof object 의 타입과 다른 타입의 키를 index signature에 넣었을 할때

 

 

 

특징

해당 옵션을 사용한다면 (set to 'true') 너무 위험하기에 사용할 때마다 아래처럼 주석을 달아주는걸 권장한다.

5.5에는 deprecation이 될 예정이라 미리 false로 변경 후 에러 경고나는 곳을 수정하는게 바람직하다

 

 

 

테스트

무조건 에러 경고가 뜨는건 아님. 

추론된 object 타입의 key가 아닌 다른 key를 indexing하는 방법으로 가져올려고 할 경우 에러 발생

 

Sample (works)

// @noImplicitAny: true
// @suppressImplicitAnyIndexErrors: false
// @strict: true
// @errors: 7053
const obj = { x: 10, foo: 3 };
console.log(obj["foo"]); // works fine!

 

Sample (failed)

// @noImplicitAny: true
// @suppressImplicitAnyIndexErrors: false
// @strict: true
// @errors: 7053

const obj = { x: 10 };
console.log(obj["foo"]);

/**
 *  Element implicitly has an 'any' type because expression of type '"foo"' can't be used to index type '{ x: number; }'.
 */ Property 'foo' does not exist on type '{ x: number; }'.(7053)

 

https://www.typescriptlang.org/tsconfig#suppressImplicitAnyIndexErrors

 

TSConfig Reference - Docs on every TSConfig option

From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project.

www.typescriptlang.org