How to fix TypeScript error: expression of type can't be used to index type All In One

发布时间 2023-09-26 15:06:33作者: xgqfrms

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

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

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