Hey, I'm having trouble implementing a common JavaScript pattern in TypeScript without resorting to using any
to ignore the types. My goal is to write a function that constructs an object based on certain conditions and returns the correct type. Here's a simplified example:
Is it feasible to make the following function work without relying on any
?
function hasAB<A extends boolean, B extends boolean>(shouldHaveA: A, shouldHaveB: B): HasAB<A, B> {
const obj: any = {}
if (shouldHaveA) obj.a = ""
if (shouldHaveB) obj.b = ""
return obj
}
type HasAB<A extends boolean, B extends boolean> =
(A extends true ? {a: string} : {}) &
(B extends true ? {b: string} : {})
const a = hasAB(true, false)
const b = hasAB(false, true)
const ab = hasAB(true, true)
The return types for a, b, and ab are accurate, but the compiler does not perform any checks on the code. For instance, you could set obj.a
twice and it would go unnoticed.