isaac_wayI
tRPC4y ago
2 replies
isaac_way

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

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"
Screenshot_2022-12-22_at_6.22.55_PM.png
Was this page helpful?