How to fix TypeScript error: expression of type can't be used to index type All In One
How to fix TypeScript error: expression of type can't be used to index type All In One
errors
Element implicitly has an 'any' type, because expression of type '' can't be used to index type ''.
solutions
type guards
// const txt = foo["txt"]
let txt;
// ✅
if('txt' in foo) {
txt = foo["txt"]
}
keyof
// const txt = foo["txt"]
// ✅
const txt = foo["txt" as keyof FooBar]
keyof
+typeof
// const txt = foo["txt"]
// ✅
type KT = keyof typeof foo;
const txt = foo["txt" as KT]
demos
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
Narrowing
type-guards
//
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#typeof-type-guards
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#instanceof-narrowing
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#control-flow-analysis
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
https://www.typescriptlang.org/docs/handbook/2/classes.html#this-based-type-guards
https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#conditional-type-constraints
typeof
//
https://www.typescriptlang.org/docs/handbook/2/typeof-types.html#the-typeof-type-operator
https://www.typescriptlang.org/docs/handbook/2/types-from-types.html#handbook-content
keyof
// The keyof operator takes an object type and produces a string or numeric literal union of its keys.
type Point = { x: number; y: number };
type P = keyof Point;
// 等价于
type P = "x" | "y":
https://www.typescriptlang.org/docs/handbook/2/keyof-types.html
https://www.typescriptlang.org/docs/handbook/2/types-from-types.html#handbook-content
https://www.typescriptlang.org/docs/handbook/compiler-options-in-msbuild.html#using-project-settings
https://www.typescriptlang.org/docs/handbook/compiler-options.html#handbook-content
cheatsheets
https://www.typescriptlang.org/cheatsheets
refs
https://bobbyhadz.com/blog/typescript-element-implicitly-has-any-type-expression
https://www.totaltypescript.com/concepts/type-string-cannot-be-used-to-index-type
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17730098.html
未经授权禁止转载,违者必究!