TypeScript TS7015: 인덱스 식이 '번호' 유형이 아니므로 요소에 암묵적으로 '임의' 유형이 있습니다.
내 Angular 2 앱에서 다음 컴파일 오류가 발생합니다.
TS7015: 인덱스 식이 '숫자' 유형이 아니므로 요소에 암묵적으로 '임의' 유형이 있습니다.
원인 코드는 다음과 같습니다.
getApplicationCount(state:string) {
return this.applicationsByState[state] ? this.applicationsByState[state].length : 0;
}
그러나 이로 인해 다음 오류가 발생하지 않습니다.
getApplicationCount(state:string) {
return this.applicationsByState[<any>state] ? this.applicationsByState[<any>state].length : 0;
}
이건 말이 안 돼요.처음 속성을 정의할 때 해결하고 싶습니다.지금 내가 쓰고 있는 건:
private applicationsByState: Array<any> = [];
그러나 누군가가 배열에서 문자열 유형을 인덱스로 사용하려고 하는 것이 문제이며 지도를 사용해야 한다고 언급했습니다.하지만 어떻게 해야 할지 모르겠어요.
도와줘서 고마워요!
키/값 데이터 구조를 원하는 경우 배열을 사용하지 마십시오.
일반 개체를 사용할 수 있습니다.
private applicationsByState: { [key: string]: any[] } = {};
getApplicationCount(state: string) {
return this.applicationsByState[state] ? this.applicationsByState[state].length : 0;
}
private applicationsByState: Map<string, any[]> = new Map<string, any[]>();
getApplicationCount(state: string) {
return this.applicationsByState.has(state) ? this.applicationsByState.get(state).length : 0;
}
OP의 직접적인 문제는 아니지만, 사용자가 자신의 관리 하에 있지 않은 라이브러리에서 이 오류가 발생하는 경우 다음을 추가하여 이 오류를 억제할 수 있습니다.
{
...
"suppressImplicitAnyIndexErrors": true,
...
}
에게tsconfig.json
파일.
창문의 물체를 사용하기 위해 이걸 사용했어요.
//in js code somewhere
window.DataManager = "My Data Manager";
//in strict typescript file
let test = (window as { [key: string]: any })["DataManager"] as string;
console.log(test); //output= My Data Manager
실제로 React를 사용하던 중 커스텀키를 통해 오브젝트의 속성을 할당했을 때 이 오류가 발생하였습니다.myObj[myKey] =
이 문제를 해결하기 위해 키오프로 사용했을 뿐입니다.
interface IMyObj { title: string; content: string; }
const myObj: IMyObj = { title: 'Hi', content: 'Hope all is well' };
const myKey: string = 'content';
myObj[myKey as keyof IMyObj] = 'All is great now!';
이를 통해 사용자 지정 문자열(myKey)이 개체(myObj) 선언에 사용한 인터페이스/유형의 속성 그룹에 속함을 Typescript에 명시적으로 알 수 있습니다.
추신: 부동산의 가치를 얻는 또 다른 방법은 Github의 닫힌 Typescript의 문제에 다음과 같이 표시됩니다.
interface IMyObj {
title: string;
content: string;
}
const myObj: IMyObj = { title: 'Hi', content: 'Hope all is well' };
const myKey: string = 'content';
const getKeyValue = <T extends object, U extends keyof T>(obj: T) => (key: U) =>
obj[key];
console.log(getKeyValue(myObj)(myKey));
tsconfig.json의 경우
compilerOptions:{
"suppressImplicitAnyIndexErrors": true,
"strictNullChecks":false,
"strictPropertyInitialization": false,
}
언급URL : https://stackoverflow.com/questions/40358434/typescript-ts7015-element-implicitly-has-an-any-type-because-index-expression
'programing' 카테고리의 다른 글
Xcode 11.0 빌드 get 오류 - 메서드의 알 수 없는 인수 유형 '_attribute__' - [RCTAppState getCurrentAppState:error:] (0) | 2023.03.06 |
---|---|
Open 생성 방법기존 Spring REST API의 API 3.0 YAML 파일? (0) | 2023.03.06 |
Powershell을 사용하여 JSON 개체를 파일에 저장하는 방법 (0) | 2023.03.06 |
각도로 페이지 제목을 설정하는 방법JS (0) | 2023.03.06 |
JsonResult를 반환하는 액션 메서드를 유닛 테스트하는 방법 (0) | 2023.03.06 |