TypeScript TS7053 Error
TS7053エラーの解決
TS7053: (TS) Element implicitly has an 'any' type beacuse expression of type 'string' can`t be used to index type 'Sample'.
No index signature with a parameter of type 'string' was found on type 'Sample'.
今回はこのTypeScriptエラーを解消します。
実行環境はReact17.0.2です。
sample.tsx
export interface Sample {
id: number,
name: string,
birth: Date
}
let data: Sample = {
id: 27,
name: 'myName',
birth: new Date(1997,9,30)
}
let sampleKeys: string[] = ['id', 'name', 'birth'];
let errSample = sampleKeys.map((strKey) => data[strKey]);
// TS7053 error at data[strKey]
解決のためには、オブジェクトのキー値の型を指定します
export interface Sample {
[Key: string]: any;
id: number,
name: string,
birth: Date
}
let data: Sample = {
id: 27,
name: 'myName',
birth: new Date(1997,9,30)
}
let sampleKeys: string[] = ['id', 'name', 'birth'];
let worksGood = sampleKeys.map((strKey) => data[strKey]);
// no error
export interface IStringKey{
[Key: string]: any;
}
export interface Sample extends IStringKey{
id: number,
// (後略) 最初と同じ
// NOTE interfaceではなくclassの場合はimplements
つれづれ
先日より初めてTypeScriptを触り始めたばかりです。AngularとReactとをそれぞれ、こいつは何者ぞ?と思いながらいじっています。
jQueryは業務でだいぶいじってきましたが、templateHTMLを活用したり、仮想DOMを用いてDOM操作をライブラリに隠蔽したり、すごい世界が広がっているようです。
TypeScriptで登場する型や自作classといった概念には、JavaやC#での開発をしていますのでどっぷり馴染んでいます。
型の無いJavaScriptのvarやlet宣言は便利なようでいて、やはり不可解な意図せぬ動作を起こしやすかったです。
型安全は良いですね。