isaac_way
isaac_way2y ago

Any typescript chads able know if it's possible to map a type to another type w generics

Not 100% sure if this is appropriate to ask here but I figured there's a lot of good TS developers on this discord.. let me know if I should remove. Is it possible to use inference to somehow map one object type to another type generically? I know we can do it w/ strings but what about full objects? IE
const A = {
s: string,
}
const AMapsTo = {
someAProperty: string,
}
const B = {
n: number,
}
const BMapsTo = {
someBProperty: string,
}
const a: A = {s: "cool"}
const b: B = {n: 0}
const aMaps: AMapsTo = {someAProperty: "cool"}
const bMap: BMapsTo = {someBProperty: "cool"}

const myMapping = [[a, aMaps], [b, bMaps]]

// Doesn't have to look exactly like this
function myBuilderFunction(myMapping) {
// ...
// Some type safe function. When called with A the type is inferred as AMapsTo
return (preMappingValue: SomeType)=>SomeTypeMapsTo
}

const fn = myBuilderFunction(myMapping);

fn(a) // Typed as AMapsTo
const A = {
s: string,
}
const AMapsTo = {
someAProperty: string,
}
const B = {
n: number,
}
const BMapsTo = {
someBProperty: string,
}
const a: A = {s: "cool"}
const b: B = {n: 0}
const aMaps: AMapsTo = {someAProperty: "cool"}
const bMap: BMapsTo = {someBProperty: "cool"}

const myMapping = [[a, aMaps], [b, bMaps]]

// Doesn't have to look exactly like this
function myBuilderFunction(myMapping) {
// ...
// Some type safe function. When called with A the type is inferred as AMapsTo
return (preMappingValue: SomeType)=>SomeTypeMapsTo
}

const fn = myBuilderFunction(myMapping);

fn(a) // Typed as AMapsTo
Doesn't have to look exactly like this but just the idea of "Given this type that can be anything type the output as some other type that associated with it"
1 Reply
isaac_way
isaac_way2y ago
Spent awhile trying to figure this out and the answer is... Yes! totally possible seems like you can actually do some pretty wild stuff w/ this. Here it's actually mapping zod fields in an object to their respective components and only allowing the props associated with the component in the "mapping" array. Uses inference on the schema prop to determine the typings of the props prop 🤯 typescript is amazing