根据TypeScript中的查找类型限制通用密钥类型 [英] Restrict generic key type based on lookup type in TypeScript

查看:52
本文介绍了根据TypeScript中的查找类型限制通用密钥类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个带有两个类型参数的函数,它们分别是 T K . T 扩展了 Record 类型,而 K 是第一种类型的键.有没有一种方法可以根据 T 中的查找类型( T [K] )限制键类型?

I'm working on a function that takes two type parameters, T and K. T extends a Record type and K is a key of the first type. Is there a way I can restrict the key type based on its lookup type (T[K]) in T?

我有以下几种类型:

type FormValue = string | number | boolean | null;

type FormValues = Record<string, FormValue>;

和以下功能:

function numericFormHelperFunc<T extends FormValues, K extends keyof T>(key: K, formValues: T) {}

有没有一种方法可以限制可用于此功能的键,以便仅允许 formValues 中具有查找类型(例如 number )的键?基本上是断言 T [K]扩展数字的一种方法.

Is there a way I can restrict which keys can be used for this function so that only keys in formValues that have lookup types of, say, number are allowed? Basically a way to assert that T[K] extends number.

例如,如果我有以下示例表单类型:

For example if I have this example form type:

type MyFormValues = {
    name: string;
    age: number;
    numPets: number;
}

我可以对 numericFormHelperFunc 添加类型限制,以便仅使用键"age" "numPets" 吗?

Can I add a type restriction to numericFormHelperFunc so that only the keys "age" and "numPets" could be used?

我正在寻找一种静态的方式来执行此操作,这样我将收到有关尝试使用 numericFormHelperFunc("name",myFormValues)的编辑器警告.还希望打字稿知道在 formValues 中查找 key 的值是特定类型,而不只是 T [K] (例如,这样就可以在不使用类型声明的情况下使用特定于数字的方法和运算符).

I'm looking for a static way to do this so that I'll get editor warnings about trying to use numericFormHelperFunc("name", myFormValues). Also would like for typescript to know that the value from looking up key in formValues is of a specific type, rather than just T[K] (e.g. so that number-specific methods and operators can be used without type assertions).

推荐答案

以下是解决方法:

type FormValue = string | number | boolean | null;

type FormValues = Record<string, FormValue>;

type MyFormValues = {
  name: string;
  age: number;
  numPets: number;
}

/**
 * Takes two arguments,
 * T - indexed type
 * Allowed - allowed types
 * 
 * Iterates through all properties and check
 * if property extends allowed value
 */
type Filter<T, Allowed> = {
  [P in keyof T]: T[P] extends Allowed ? P : never
}[keyof T]

function numericFormHelperFunc<T extends FormValues>(key: Filter<MyFormValues, number>, formValues: T) { }

numericFormHelperFunc('age', {'sdf':'sdf'}) // ok
numericFormHelperFunc('numPets', {'sdf':'sdf'}) // ok
numericFormHelperFunc('hello', {'sdf':'sdf'}) // error
numericFormHelperFunc('2', {'sdf':'sdf'}) // error
numericFormHelperFunc('name', {'sdf':'sdf'}) // error

这篇关于根据TypeScript中的查找类型限制通用密钥类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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