Typescript

awesome.cube.dev
Data visualisation tools

paykit.sh
Payment library
/**
* Check if a Number is a power of ten (10, 100, 1000...)
*/
const isPowerOfTen = (n: number) => Math.log10(n) % 1 === 0;
isPowerOfTen
/**
* List of types with different properties
*/
type Animal =
| {
name: "cat";
hair: "long" | "short";
}
| {
name: "dog";
hair: "long" | "short";
}
| {
name: "fish";
scale: "blue" | "grey";
};
/**
* Type of animal name
*/
type AnimalName = Animal["name"];
/**
* Type of animal with the property hair
*/
type AnimalWithHair = Animal extends infer Parent
? // biome-ignore lint/suspicious/noExplicitAny: <explanation>
Parent extends { hair: any }
? Parent
: never
: never;
/**
* Hair type for animal with this name
*/
type AnimalHair<
Name extends AnimalName,
CurrentAnimal = Animal extends infer Parent
? Parent extends { name: Name }
? Parent
: never
: never,
Method = CurrentAnimal extends AnimalWithHair ? CurrentAnimal["hair"] : never,
> = Method;
/**
* Random animal
*/
const animal = [
{ name: "cat", hair: "short" },
{ name: "dog", hair: "short" },
{ name: "fish", scale: "blue" },
][Math.floor(3 * Math.random())];
/**
* Test if the animal has same properties with Typescript arguments autocompletion
*/
function testAnimal<Name extends AnimalName>(
name: Name,
hair?: AnimalHair<Name>,
) {
return (
name === animal.name &&
(hair ? hair === (animal as AnimalWithHair).hair : true)
);
}
testAnimal("fish");
testAnimal("cat", "long");
Deep property inference
/**
* Extract a generic of a type
**/
// Your type
type TypeWithGeneric<T> = T[]
// Extract a generic from a type (helper)
type ExtractGeneric<Type> = Type extends TypeWithGeneric<infer X> ? X : Type
// Use
type extracted = ExtractGeneric<TypeWithGeneric<number>>