通用函数输入中的键的强制类型 [英] Enforcing type of key in generic function input

查看:49
本文介绍了通用函数输入中的键的强制类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有通用功能:

function f<T, K extends keyof T>(obj: T, key: K) {
   ...
}

我想强制使用 T [K] 的类型,以便执行特定于类型的操作.例如,使用字符串:

I would like to enforce the type of T[K] so I could perform type specific actions. For example, using string:

function f<T, K extends keyof T>(obj: T, key: K): string {
    return obj[key].toLowerCase();
}

在不将内容强制转换为任何的情况下,这完全可能吗?

Is this at all possible without casting things to any?

修改:为了明确起见,我正在寻找能够根据结果类型禁止某些键的功能.使用上面的示例,类似:

To clarify, I'm looking for the ability to disallow certain keys based on the resulting type. Using the example above, something like:

f({a: 123, b: 'abc'}, 'b') //No errors
f({a: 123, b: 'abc'}, 'a') //Typescript error, T['a'] is not string

推荐答案

要将属性名称限制为仅具有 string 值类型的属性,可以将条件类型与映射类型结合使用:

To restrict property names to only those having string value types you can use conditional types in conjunction with mapped types:

type StringProperties<T> = { [K in keyof T]: T[K] extends string ? K : never }[keyof T];

declare function f<T>(obj: T, key: StringProperties<T>): string;

f({a: 123, b: 'abc'}, 'b') // No errors
f({a: 123, b: 'abc'}, 'a') // Error: Argument of type '"a"' is not assignable to parameter of type '"b"'.

游乐场

这篇关于通用函数输入中的键的强制类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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