I'm trying to create a few generic recursive types to modify structure of existing types. I can't tell why the sections inferring arrays and nested objects is not getting triggered. Any idea what I'm doing wrong?
TS playround link with the below code:
//Generics
type WithConfidence<T> = {
[Property in keyof T]: {
value: FieldWithConfidence<T[Property]>;
confidence: number;
};
};
type FieldWithConfidence<T> = {
[P in keyof T]: T[P] extends string | number | Date
? T[P]
: T[P] extends Array<infer U>
? {
confidence: number;
value: Array<WithConfidence<U>>;
}
: {
value: FieldWithConfidence<T[P]>;
confidence: number;
};
};
It works for primitive types and when the type is an object, just not an array. Here's an example illustrating where it falls short.
type Asset = {
AssetCode?: string;
Contracts?: Array<Contract>;
Warranty: WarrantyInfo;
};
type Contract = {
ContractNumber: string;
};
type WarrantyInfo = {
Purchased: Date;
};
const value: WithConfidence<Asset> = {
Warranty: {
confidence: 500,
value: {
Purchased: {
value: new Date(), //Error
confidence: 500,
},
},
},
AssetCode: {
value: "123",
confidence: 100,
},
Contracts: {
confidence: 400,
value: [
{
ContractNumber: { //Error
value: "123",
confidence: 500,
},
},
],
},
};
Contractsarray being an object with a plainContractNumberproperty (not turned into a confidence-value object itself), but with aconfidenceproperty alongside that property. However, in your sample data, you haveContractNumberturned into a confidence-value object, consistent with the rest of the pattern. I assume you intend the latter?