gpt4 book ai didi

typescript - 根据 TypeScript 中的查找类型限制通用键类型

转载 作者:行者123 更新时间:2023-12-01 23:38:30 25 4
gpt4 key购买 nike

我正在研究一个函数,该函数采用两个类型参数,TKT 扩展了 Record 类型,K 是第一种类型的键。有没有一种方法可以根据 T 中的查找类型 (T[K]) 来限制 key 类型?

我有以下类型:

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] extends number 的方法。

例如,如果我有这个示例表单类型:

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

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

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

最佳答案

解决方法如下:

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 - 根据 TypeScript 中的查找类型限制通用键类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65241412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com