gpt4 book ai didi

typescript - 根据 Typescript 中同级属性的泛型类型推断类型

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

我想根据属性的同级属性的泛型类型来定义属性的类型。

例如,假设我们有:

type Person = {
id: number;
name: string;
}

type Select<Value=unknown> = (props:Props<Value>) => any;

const PersonSelect:Select<Person> = (props) => null //implementation is irrelavant
const TextSelect:Select<string> = (props) => null //implementation is irrelavant


然后我希望能够做这样的事情:


type Filter<V = unknown > = {
component: Select<V>,
transformer: (value: V) => string
};

const filters:Array<Filter> = [
{
component: PersonSelect,
transformer: (selected) => selected.name //type of `selected` should be infered as `Person`
},
{
component: TextSelect,
transformer: (selected) => selected // type of `selected` should be infered as `string`
}
]


解决方法

通过上面的代码我可以做到这一点



const personFilter:Filter<Person> = {
component: PersonSelect,
transformer: (selected) => selected.name
}
const textFilter:Filter<string> = {
component: TextSelect,
transformer: (selected) => selected
}

const filters = [personFilter, textFilter];

但我正在寻找一种无需显式定义每个过滤器对象类型即可工作的解决方案。此外,通用 V 类型可以是任何类型,所以我不能使用所有可能组合的并集。

有没有更好的解决方案?

最佳答案

似乎 TypeScript 很难根据同一对象的其他属性推断箭头函数属性参数。

在函数推断的帮助下我无法做到这一点。

最简单的方法是制作builder返回 Filter<_> 的函数.


type Person = {
id: number;
name: string;
}

type Props<T> = T

type Select<Value = unknown> = (props: Props<Value>) => any;

const PersonSelect: Select<Person> = (props) => null //implementation is irrelavant

const TextSelect: Select<string> = (props) => null //implementation is irrelavant

type Filter<V = unknown> = {
component: Select<V>,
transformer: <T extends V>(value: T & V) => string
};


const builder = <V,>(
component: Select<V>,
transformer: (value: V) => string
): Filter<V> =>
({ component, transformer })

const filters = [
builder(PersonSelect, (selected) => selected.name),
builder(TextSelect, (selected) => selected)
]

Playground

因为 componenttransformer参数不是同一数据结构的一部分,更容易推断它们并应用我们的类型约束。

Here ,您可以找到更多有关函数参数类型推断的示例。

关于typescript - 根据 Typescript 中同级属性的泛型类型推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69254779/

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