I want to implement a sorting function that can take the value of an object using a function, but at the moment I can't infer the return value of the function that takes the value.
type TKey<TData> = ((data: TData) => any) interface SortingConfig< TData, TExtractor extends TKey<TData>, TValue = TExtractor extends (data: TData) => infer R ? R : never> { extractor: TExtractor, comparator?: (a: TValue, b: TValue) => number } function test1<TData, TExtractor extends TKey<TData>>( value: TData, conf: SortingConfig<TData, TExtractor> ) {} test1({ a: 1, b: "string" }, { // extractor type: (data: {a: number, b: string}) => string // The type of comparator is wrong, parameter type should be the return type of extractor extractor: data => data.b, // comparator type: (a: any, b: any) => any // expect: (a: string, b: string) => number comparator: (a, b) => a }) /** * This works, but unfortunately I need to write it in the above way */ function test2< TData, TExtractor extends TKey<TData>, TValue = TExtractor extends (data: TData) => infer R ? R : never >( data: TData, extractor: TExtractor, comparator: (a: TValue, b: TValue) => number ) {} // Put the comparator and extractor outside the conf object and it works // extractor type: (data: {a: number, b: string}) => number // comparator type: (a: number, b: number) => number test2({a: 1, b: "string"}, data => data.a, (a, b) => a) https://stackoverflow.com/questions/66077029/how-to-infer-type-parameters-from-other-type-parameters February 06, 2021 at 08:40PM
没有评论:
发表评论