xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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 ''.

image

https://stackoverflow.com/questions/77177225/how-to-access-the-string-index-of-a-typescript-type-that-mixes-known-and-unknown/77177386#77177386

https://stackoverflow.com/questions/63430129/how-to-mix-index-signature-with-known-properties/63430341#63430341

solutions

  1. type guards
// const txt = foo["txt"]

let txt;
// ✅
if('txt' in foo) {
   txt = foo["txt"]
}

TypeScript Playground

  1. keyof
// const txt = foo["txt"]

// ✅
const txt = foo["txt" as keyof FooBar]

  1. keyof + typeof
// const txt = foo["txt"]

// ✅
type KT = keyof typeof foo;
const txt = foo["txt" as KT]

demos

TypeScript Playground

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 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

image

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, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-09-26 14:53  xgqfrms  阅读(89)  评论(0编辑  收藏  举报