- GitHub - gvergnaud/hotscript: A library of composable functions for the type-level! Transform your TypeScript types in any way you want using functions you already know.
- A library of composable functions for the type-level! Transform your TypeScript types in any way you want using functions you already know. - gvergnaud/hotscript
This post has been translated by AI.
Post summarized by durumis AI
- Manually typing types in TypeScript can reduce readability, and using higher-order types can define them more cleanly.
- By leveraging the hotscript library, you can concisely manage type definitions based on higher-order types.
- We recommend using the hotscript library, which offers various features, to improve code readability and utilize it as needed.
Let's take an example of a piece of code.
It's a code that converts the first letter of each word to UpperCase.
const firstLetterUpperCase = (str : string) => { return str.split(" ").map(v => ${v.charAt(0).toUpperCase()}${v.slice(1)}).join(" "); } console.log(firstLetterUpperCase("hello world"));
It's simple, but this makes the return type string, and type inference becomes impossible.
type FirstLetterUppercase = T extends ${infer R}${infer RestWord} ${infer RestSentence} ? ${Uppercase<R>}${RestWord} ${FirstLetterUppercase<RestSentence>} : T extends ${infer R}${infer RestWord} ? ${Uppercase<R>}${RestWord} : never; const firstLetterUpperCase= (str : T) : FirstLetterUppercase => { return str.split(" ").map(v => ${v.charAt(0).toUpperCase()}${v.slice(1)}).join(" ") as FirstLetterUppercase ; } console.log(firstLetterUpperCase("hello world"));
Of course, you can type each type one by one like above.
However, the above type feels less readable. Nested ternary operators and recursive structures are the problem, right?
But surprisingly, TypeScript supports higher-order types.
And there's a higher-order type library based on that higher-order type.
You can use this library to neatly organize type definitions.
type FirstLetterUppercase2= Pipe< T, [ Strings.Split<" ">, Tuples.Map<Strings.Capitalize>, Tuples.Join<" "> ] >; type A = FirstLetterUppercase2<"hello world">; // ^? type = "Hello World"
The code is here.
In this way, we can organize types in a more readable way using higher-order types.
There are various other features, so it's good to visit the site, take a look around, and use it when you need it.