Created
September 30, 2021 16:06
-
-
Save JavierCane/5e6bacaf3084a2be20a44cc30923763f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type MethodKeys<T> = ({ [P in keyof T]: T[P] extends Function ? P : never })[keyof T]; | |
type ClassProps<T> = { | |
[key in keyof T]: | |
T[key] extends { value: any } | |
? Pick<T[key], "value">["value"] | |
: T[key] extends Object | |
? ValueObjectPrimitives<T[key]> | |
: T[key]; | |
}; | |
type ValueObjectPrimitives<T> = Omit<ClassProps<T>, MethodKeys<T>>; | |
// https://flut1.medium.com/deep-flatten-typescript-types-with-finite-recursion-cb79233d93ca | |
/////////////// START LO DEL FLATTEN | |
type NonObjectKeysOf<T> = { | |
[K in keyof T]: T[K] extends Array<any> ? | |
K : | |
T[K] extends object ? never : K | |
}[keyof T]; | |
type NonObjectPropertiesOf<T> = Pick<T, NonObjectKeysOf<T>>; | |
type ValuesOf<T> = T[keyof T]; | |
type ObjectValuesOf<T> = Exclude< | |
Extract<ValuesOf<T>, object>, | |
Array<any> | |
>; | |
type SubPropertiesOf<T> = { | |
[K in keyof ObjectValuesOf<T>]: ObjectValuesOf<T>[K] | |
}; | |
type Flatten<T> = NonObjectPropertiesOf<T> & SubPropertiesOf<T>; | |
///////////////////// END LO DEL FLATTEN | |
type PatataPrimitives = ValueObjectPrimitives<Patata>; | |
type FlattenPatataPrimitives = Flatten<ValueObjectPrimitives<Patata>>; | |
const cosa: PatataPrimitives = { | |
address: '1231231', | |
postCode: 123, | |
combinacion: { | |
numberProp: 123, | |
stringProp: '123131' | |
} | |
}; | |
const cosaFlatten: FlattenPatataPrimitives = { | |
address: '1231231', | |
postCode: 123, | |
numberProp: 123, | |
stringProp: '123131', | |
}; | |
class StringValue { | |
constructor(readonly value: string) { } | |
toString(): string { | |
return this.value; | |
} | |
} | |
class NumberValue { | |
constructor(readonly value: number) { } | |
toString(): string { | |
return this.value.toString(); | |
} | |
} | |
class CombinacionDeValue { | |
constructor( | |
readonly stringProp: StringValue, | |
readonly numberProp: NumberValue, | |
) { } | |
toPrimitives() { | |
return { stringProp: this.stringProp, numberProp: this.numberProp }; | |
} | |
} | |
class Patata { | |
constructor( | |
readonly address: StringValue, | |
readonly postCode: NumberValue, | |
readonly combinacion: CombinacionDeValue | |
) { } | |
toPrimitives() { | |
return "patata"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment