你怎么能表达“keyof T"?成为字符串的子集? [英] how can you express "keyof T" to be a subset of String?

查看:29
本文介绍了你怎么能表达“keyof T"?成为字符串的子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Firebase 类型有一个接口 IQuery,其中 equalTo() 方法类型为:

The Firebase typings have an interface IQuery which has the equalTo() method typed as:

public equalTo(value: number | string | boolean | null, name?: string): IQuery;

我有一个模拟库,它试图模仿 Firebase 公开的 API 表面,但在 name 参数的情况下,字符串"的一般类型可以更具体:

I have a mocking library which is trying to mimic the API surface of what Firebase is exposing but in the case of the name parameter the general typing of "string" can be made more specific:

 public equalTo(value: number | string | boolean | null, key?: keyof T): IQuery<T>

通过声明 keyof T 我们得到了一些我不想失去的非常有用的静态检查,事实上直到 TypeScript 2.8.3 我似乎能够做到这一点,但是在移动时到 2.9.x+ 的 Typescript 我现在得到这个错误:

By stating keyof T we get some very useful static checking that I'd hate to lose out on and in fact up to TypeScript 2.8.3 I seemed to be able to do this but when moving to 2.9.x+ of Typescript I now get this error:

类型 'string' 不可分配给类型 'keyof T'.

Type 'string' is not assignable to type 'keyof T'.

更多的上下文,我的模拟库中的类定义是:

For a bit more context, the class definition in my mocking library is:

 export default class Query<T = any> implements IQuery<T> { ... }

其中 泛型类型是查询将返回的数据结构类型的指示符.

Where the <T> generic type is an indicator of type of the data structure that the query will return.

另外值得注意的是,T,将始终被塑造成一个带有字符串键的字典/哈希,因此 keyof T 将是字符串值的子集,但在我的输入中我没有说清楚,所以我知道 Typescript 的问题在哪里......我只是不知道如何表达 keyof T 必须是一个字符串.

Further it is worth noting that T, will always be shaped as a dictionary/hash with string keys and therefore keyof T will subset of string values but in my typing I'm not making this clear so I get where Typescript is taking issue ... I just don't know how to express that keyof T must be a string.

推荐答案

这与 2.9 中 keyof 工作方式的改变有关,直到 2.9 keyof 才返回string 键,从 2.9 开始它将返回 numbersymbol 键.这是this的参考

This is related to a change in the way keyof works in 2.9, until 2.9 keyof only returned string keys, from 2.9 onward it will return number and symbol keys. This is the reference for this

要仅接受 string 键,您可以使用 Extract 作为 key 参数的类型,或者如果您想要恢复到旧的行为,你可以使用 --keyofStringsOnly 编译器标志

To only accept string keys you can use Extract<keyof T, string> as the type for the key parameter, or if you want to revert to the old behavior you can use the --keyofStringsOnly compiler flag

public equalTo(value: number | string | boolean | null, key?: Extract<keyof T, string>): IQuery<T>

这篇关于你怎么能表达“keyof T"?成为字符串的子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆