ethanbehrends
ethanbehrends
TTCTheo's Typesafe Cult
Created by ethanbehrends on 7/17/2023 in #questions
Utility type to "undiscriminate" a discriminated union
So this might be kind of a hacky thing, but I've got a use case that could greatly benefit from it. Basically, imagine I have the following type:
type DiscriminatedUnion = {
type: "image"
imageUrl: string
} | {
type: "text"
body: string
}
type DiscriminatedUnion = {
type: "image"
imageUrl: string
} | {
type: "text"
body: string
}
I've been trying to make a utility type essentially flatten this type into something like this:
type FlattenDiscriminatedUnion<Union, Field extends string> = {
// ?????
}

// FlattenDiscriminatedUnion<DiscriminatedUnion, "type"> === {
// type: "image" | "text"
// imageUrl?: string
// body?: string
//}
type FlattenDiscriminatedUnion<Union, Field extends string> = {
// ?????
}

// FlattenDiscriminatedUnion<DiscriminatedUnion, "type"> === {
// type: "image" | "text"
// imageUrl?: string
// body?: string
//}
This may be pushing the limits of TS, but was hoping some wizardry could be done to solve this. Does this sound like something that's even possible? I've been trying to make it happen for a while but can't seem to get it to work.
2 replies
TTCTheo's Typesafe Cult
Created by ethanbehrends on 3/21/2023 in #questions
Is there a way to make Typescript smarter when implementing a class?
class AbstractClass {
testMethod: (a: string, b: number) => Promise<boolean>
testMethodTwo: (a: string, b: number) => Promise<boolean>
}

class TSClass implements AbstractClass {
async testMethod(a, b) { // no intellisense

return true
}
async testMethodTwo(a: string, b: number) {

return true
}
}
class AbstractClass {
testMethod: (a: string, b: number) => Promise<boolean>
testMethodTwo: (a: string, b: number) => Promise<boolean>
}

class TSClass implements AbstractClass {
async testMethod(a, b) { // no intellisense

return true
}
async testMethodTwo(a: string, b: number) {

return true
}
}
In short, I want to get Intellisense on testMethod without needing the explicit typing like on testMethodTwo. Context: I'm trying to (slowly) introduce Typescript to a legacy-ish codebase, and wanting to make it as easy as possible for the rest of the team to learn and move fast. It would be nice if I could lay out some scaffolding (AbstractClass) and get Intellisense without the team needing to know how to use TS syntax .
1 replies