Update: it looks like for the behaviour desired, TypeScript requires existential generic types - and as if TS 4.1 it doesn't have them. Thanks the helpful answer. I think to solve the typing react-query useQueries
there is still a way forward whereby we use unknown
when selector
is supplied. I'll try and make that work and see where it goes.
Consider the following:
interface Data<TData = unknown, TSelected = unknown> {
data: TData;
selector?: (data: TData) => TSelected
}
function makeArrayAsConstItemsForDataTypesOnly<
TItem extends readonly Data[]
>(arr: [...TItem]): { [K in keyof TItem]: { item: Extract<TItem[K], Data>["data"] } } {
return arr.map(item => {
return item.selector
? { item: item.selector(item.data) }
: { item: item.data }
}) as any;
}
const returnedData = makeArrayAsConstItemsForDataTypesOnly([
{ data: { nested: 'thing' }, selector: d => d.nested },
{ data: 1 },
{ data: 'two' }])
returnedData
takes the type:
const returnedData: [{
item: {
nested: string;
};
}, {
item: number;
}, {
item: string;
}]
A selector
may or may not be supplied with each element. If supplied, it maps over the supplied data
type and transforms the returned data.
Given the above example, then ideally the returned type would be:
const returnedData: [{
item: string;
}, {
item: number;
}, {
item: string;
}]
Alas it isn't, also, in selector: d => d.nested
, d
takes the type unknown
as opposed to the type TData
. So we aren't getting the type inference flowing through as hoped.
Pseudo-code for the return type would look like this:
- for each entry of the array:
- get the
data
property
- if the array entry contains a
selector
then return { item: entry.selector(entry.data) }
- else return
{ item: entry.data }
Is it possible to express this via the type system in TypeScript? See playground here.
So there's two problems here:
selector
flowing through TData
as the input
- the return type of the overall function
question from:
https://stackoverflow.com/questions/65644828/typescript-dependant-type-inference-with-variadic-tuple-types 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…