Created
January 8, 2022 07:56
-
-
Save Neo42/98b27bffb254f602b073d6055bb487da 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 AppleLiteral = 'Apple' | |
let appleName: AppleLiteral = 'Apple' | |
type LiteralIsStringType<Type> = Type extends string | |
? string | |
: Type extends number | |
? number | |
: Type extends boolean | |
? boolean | |
: never | |
type AppleLiteralType = LiteralIsStringType<AppleLiteral> // string | |
type NonNullableApple = NonNullable<AppleLiteral> // 'Apple' | |
type ExcludeFromUnion<Type, Union> = Type extends Union ? never : Type | |
type FavoriteLetters = 'h' | 'a' | 'o' | |
type Vowels = 'a' | 'e' | 'i' | 'o' | 'u' | |
type NonFavoriteVowels = ExcludeFromUnion<Vowels, FavoriteLetters> | |
type ExtractFromUnion<Type, Union> = Type extends Union ? Type : never | |
type FavoriteVowels = ExtractFromUnion<Vowels, FavoriteLetters> | |
addClassNameToElement(document.getElementsByTagName('div')[0], 'fruit-list-div') | |
function addClassNameToElement(element: unknown, className: string) { | |
// element.classList.add(className) | |
} | |
// for any functions, if the function corresponds to this type annotation, | |
// in which the type of the return value can be inferred automatically by TypeScript, | |
// return the inferred type of the return value, otherwise just return any | |
type ReturnFunctionType<Type extends (...args: any) => any> = Type extends ( | |
...args: any | |
) => infer RType | |
? RType | |
: any | |
// for any functions, if the function corresponds to this type annotation, | |
// in which the type of the second parameter can be inferred automatically by TypeScript, | |
// return the inferred type of the second parameter, otherwise just return any | |
type SecondParameterType<Type extends (...args: any) => any> = Type extends ( | |
arg1: any, | |
arg2: infer SecondParam, | |
) => any | |
? SecondParam | |
: any | |
type ClassNameSecondParam = SecondParameterType<typeof addClassNameToElement> | |
// for any types, if the type corresponding the annotation, | |
// which is an array and in which the type of the element can be inferred | |
// then return the inferred type of the element, otherwise return the original type | |
type UnwrapArray<Type> = Type extends (infer Element)[] ? Element : Type | |
// for any types, if the type corresponding the annotation, | |
// which is a promise and whose the type of the resolved value can be inferred | |
// then return the inferred type of the resolved value, otherwise return the original type | |
type UnwrapPromise<Type> = Type extends Promise<infer ResolvedValue> | |
? ResolvedValue | |
: Type |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment