Created
August 13, 2018 11:34
-
-
Save dragomirtitian/696bcba440342aaa8fc964d1fcca5075 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
enum Option { Some = 1, Empty = 2 } | |
type DistributeOptionValue<T> = T extends null | undefined ? OptionValue<T, Option.Empty> : OptionValue<T, Option.Some>; | |
interface OptionValue<T, O extends Option> { | |
option: O; | |
value: T; | |
} | |
function getValue<T>(value: T): DistributeOptionValue<T> | |
function getValue<T>(value: T): OptionValue<T, Option> { | |
return ({ | |
option: value ? Option.Some : Option.Empty, | |
value | |
}); | |
} | |
type GetOptionValue<T extends OptionValue<any, Option>> = | |
T extends OptionValue<infer U, infer O> ? O extends Option.Empty ? Option.Empty: U : never; | |
let handleSomeValue = <T extends OptionValue<any, Option>>(obj: T): GetOptionValue<T> => { | |
switch (obj.option) { | |
case Option.Some: | |
return obj.value; | |
default: | |
return Option.Empty as GetOptionValue<T>; | |
} | |
} | |
let someStringValue = 'check'; // type string | |
let result1 = handleSomeValue(getValue(someStringValue)); // it is 'string' correctly | |
let someNumberValue = 22; | |
let result2 = handleSomeValue(getValue(someNumberValue)); //is number | |
let someStringOrUndefinedValue: string | null | undefined = Math.random() > 0.5 ? "" : undefined; | |
let uu = getValue(someStringOrUndefinedValue); | |
let result3 = handleSomeValue(getValue(someStringOrUndefinedValue)); // is string | Option.Empty | |
let someUndefinedValue: undefined = undefined; | |
let result4 = handleSomeValue(getValue(someUndefinedValue)); // is Option.Empty | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment