简体   繁体   English

Typescript 中未推断的索引类型

[英]Index Types not Inferring in Typescript

I have a small code where TS drives me crazy...我有一个小代码,TS 让我发疯......

type MyCustomType<T extends Record<string, string>> = {
  key: keyof T;
};

export const myFunction = <T extends Record<string, string>>(variable: MyCustomType<T>) => {
  const newVar: string = variable.key;
};

Typescript keeps complaining that variable.key can be string | Typescript 一直抱怨variable.key可以是字符串 | number |号码 | symbol and can't be assign to newVar .符号并且不能分配给newVar But I typed my generic object as Record<string, string> .但是我输入了我的通用 object 作为Record<string, string>

So, why TS can't guess it's a string?那么,为什么 TS 猜不出它是一个字符串呢?

How can I type these, without using as我怎样才能输入这些,而不使用as

Thanks a lot !非常感谢 !

The compiler does not infer keyof T to be string because it does not have to be a string .编译器不会将keyof T推断为string ,因为它不必是string Your constraint merely states that every string key must have a string value.您的约束仅说明每个string键都必须有一个string值。 But T might also have number or symbol keys.T也可能有numbersymbol键。

myFunction<Record<0, string>>({ key: 0 })
// no error, the constraint is fulfilled

So we should explicitly forbid number and symbol keys.所以我们应该明确禁止numbersymbol键。

type MyCustomType<
  T extends Record<string, string> 
    & Record<number | symbol, never>
> = {
  key: keyof T & string;
};

export const myFunction = <
  T extends Record<string, string> 
    & Record<number | symbol, never>
>(variable: MyCustomType<T>) => {
  const newVar: string = variable.key;
  console.log(newVar)
};

This still does not silence the error.这仍然不能消除错误。 TypeScript is not able to deduct that keyof T is a string . TypeScript 无法keyof T是一个string After all, it could still have number properties of type never (which practically is not possible but you could still explicitly pass a type containing never values).毕竟,它仍然可以具有never类型的number属性(这实际上是不可能的,但您仍然可以显式传递包含never值的类型)。 But we can now "safely" intersect keyof T with string .但是我们现在可以“安全地” keyof Tstring相交。

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM