iTranslated by AI
Introduction to Useful TypeScript Tips and Snippets
Introduction
I'm writing about things I found useful while working with TypeScript or reading articles, but weren't substantial enough to warrant their own dedicated posts. This is essentially a memorandum, but I believe it will be helpful, so please take a look.
How to convert an object's property list into an array of union types
Overall code
const getKeys = <T extends { [key: string]: unknown }>(obj: T): (keyof T)[] => {
return Object.keys(obj);
};
Brief explanation
TypeScript generics are an important feature for writing flexible and type-safe code. Generics allow you to define functions or classes without depending on a specific type by parameterizing the type. For example, consider the following function:
function identity<T>(arg: T): T {
return arg;
}
This identity function defines the type of the argument arg as a generic type T. The return type of the function is also T. This allows the type to be determined dynamically based on the value of the type specified when calling the function. For instance, you can call the identity function as follows:
const str = identity<string>("Hello");
console.log(str); // Output: 'Hello'
const num = identity<number>(42);
console.log(num); // Output: 42
In identity<string>('Hello'), T is set to the string type, and the argument 'Hello' is returned as is. Similarly, in identity<number>(42), T is set to the number type, and the argument 42 is returned. Furthermore, by using type inference, you can call the function without explicitly specifying the type argument.
const str2 = identity("Hello");
console.log(str2); // Output: 'Hello'
const num2 = identity(42);
console.log(num2); // Output: 42
In this case, TypeScript automatically infers the type argument T from the type of the argument. str2 is inferred as the string type, and num2 as the number type. Additionally, you can set constraints (limitations) on generic types. This allows you to require that parameters for a generic type meet specific conditions. You set constraints using the extends keyword as follows:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
This getProperty function takes an object obj and its property name key, and returns the corresponding value. The generic type T represents the type of the object, and K represents the type of the property name of that object. The constraint K extends keyof T ensures that K must be one of the property names of T. If you try calling the getProperty function, specifying an object for the first argument will cause the second argument to require a property of that object. In this way, generic types allow for a certain degree of freedom while maintaining specific rules through type constraints.
Now, let's implement a function to get object properties as an array of union types.
const getKeys = <T extends { [key: string]: unknown }>(obj: T): (keyof T)[] => {
return Object.keys(obj);
};
This getKeys function uses the generic type T to represent the type of the object. The constraint T extends { [key: string]: unknown } requires T to be an object type. Inside the function, Object.keys(obj) is used to retrieve the property names of the object as an array of strings. Through TypeScript's type inference, the return value of Object.keys(obj) is inferred as the (keyof T)[] type—that is, an array of the union type of T's property names. As a result, an array of the desired type is returned without using explicit assertions. It can be used as follows:
const person = {
name: "John",
age: 30,
city: "New York",
};
const keys = getKeys(person);
console.log(keys); // Output: ['name', 'age', 'city']
By passing the person object to the getKeys function, an array of the union type of its property names is returned.
References
https://zenn.dev/ossamoon/articles/694a601ee62526
Creating an array with all combinations of a union type
Completed code
type Permutation<T, K = T> = [T] extends [never]
? []
: K extends K
? [K, ...Permutation<Exclude<T, K>>]
: never;
I am copying this code entirely from here.
Brief explanation
The TypeScript type system offers various advanced type features such as union types, conditional types, mapped types, and template literal types. One particularly powerful feature among them is Distributive Conditional Types.
Distributive conditional types refer to the behavior where applying a conditional type to a union type results in the conditional type being applied individually to each constituent element of the union type.
In other words, a conditional type in the following format is treated as a distributive conditional type:
(A | B | C) extends U ? X : Y
This conditional type is evaluated as follows:
(A extends U ? X : Y) | (B extends U ? X : Y) | (C extends U ? X : Y)
For example, consider the following conditional type:
type Example<T> = T extends string ? true : false;
When you apply the union type string | number to this conditional type, it looks like this:
type Result = Example<string | number>;
The type of Result is evaluated as follows:
(string extends string ? true : false) | (number extends string ? true : false)
Since string extends string evaluates to true and number extends string evaluates to false, the final type of Result becomes true | false.
Additionally, TypeScript allows for recursive type definitions. By using recursive type definitions, you can represent complex data structures and algorithms at the type level.
Additionally, TypeScript also allows for recursive type definitions. By using recursive type definitions, you can represent complex data structures and algorithms at the type level.
For example, consider the following recursive type definition:
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
This DeepReadonly type recursively makes the properties of an object readonly.
If a property of the object is itself an object, DeepReadonly is applied recursively.
For instance, consider the following type:
interface Person {
name: string;
age: number;
address: {
street: string;
city: string;
};
}
Applying DeepReadonly to this Person type results in the following:
type ReadonlyPerson = DeepReadonly<Person>;
The type of ReadonlyPerson is evaluated as follows:
{
readonly name: string;
readonly age: number;
readonly address: {
readonly street: string;
readonly city: string;
};
}
Since the address property is also an object, DeepReadonly is applied recursively, making the properties of the address object readonly as well.
In this way, recursive type definitions allow for type-level operations on complex data structures.
By combining these features, you can create complex type definitions like the Permutation type.
type Permutation<T, K = T> = [T] extends [never]
? []
: K extends K
? [K, ...Permutation<Exclude<T, K>>]
: never;
The Permutation type generates a type representing all permutations of a union type T. For example, Permutation<'a' | 'b' | 'c'> results in the following union type:
["a", "b", "c"] |
["a", "c", "b"] |
["b", "a", "c"] |
["b", "c", "a"] |
["c", "a", "b"] |
["c", "b", "a"];
In this type definition, distributive conditional types and recursive type definitions are combined.
First, in the part [T] extends [never] ? [] : ..., it returns an empty array type ([]) if T is an empty union type (never). This serves as the base case.
Next, in the part K extends K ? [K, ...Permutation<Exclude<T, K>>] : never, a distributive conditional type is used. Here, K is applied individually to each constituent element of the union type T. While K extends K is always true, the behavior of distributive conditional types ensures that K is applied separately to each element of the union type.
For example, in the case of Permutation<'a' | 'b' | 'c'>, in the first step, K is 'a' | 'b' | 'c'. Then, due to the behavior of distributive conditional types, it is evaluated as follows:
('a' extends 'a' | 'b' | 'c' ? ['a', ...Permutation<Exclude<'a' | 'b' | 'c', 'a'>>] : never) |
('b' extends 'a' | 'b' | 'c' ? ['b', ...Permutation<Exclude<'a' | 'b' | 'c', 'b'>>] : never) |
('c' extends 'a' | 'b' | 'c' ? ['c', ...Permutation<Exclude<'a' | 'b' | 'c', 'c'>>] : never)
As a result, the Permutation type is applied recursively to each of 'a', 'b', and 'c'.
In the part [K, ...Permutation<Exclude<T, K>>], the current element K is placed at the beginning of the array, and the Permutation type is applied recursively to the remaining elements. Exclude<T, K> is a union type representing the remaining elements of T after excluding K.
This recursive process generates all permutations of the union type T.
The following shows the evaluation flow of Permutation<'a' | 'b' | 'c'>:
-
Case of
'a':['a', ...Permutation<Exclude<'a' | 'b' | 'c', 'a'>>]['a', ...Permutation<'b' | 'c'>]['a', 'b', 'c'] | ['a', 'c', 'b']
-
Case of
'b':['b', ...Permutation<Exclude<'a' | 'b' | 'c', 'b'>>]['b', ...Permutation<'a' | 'c'>]['b', 'a', 'c'] | ['b', 'c', 'a']
-
Case of
'c':['c', ...Permutation<Exclude<'a' | 'b' | 'c', 'c'>>]['c', ...Permutation<'a' | 'b'>]['c', 'a', 'b'] | ['c', 'b', 'a']
Finally, these union types are combined to become ['a', 'b', 'c'] | ['a', 'c', 'b'] | ['b', 'a', 'c'] | ['b', 'c', 'a'] | ['c', 'a', 'b'] | ['c', 'b', 'a'].
In this way, the Permutation type expresses all permutations of a union type by combining distributive conditional types and recursive type definitions. Distributive conditional types are a powerful feature that applies a conditional type individually to each constituent element of a union type, and by combining them with recursive type definitions, complex type-level algorithms can be achieved.
References
https://mosya.dev/blog/tc-permutation
https://github.com/type-challenges/type-challenges/issues/614
Rebuilding an array of objects by merging matching objects using an arbitrary property as a key
Completed code
type ObjectType = {
[key: string]: string;
} & { id: string };
const a: ObjectType[] = [
{ id: "id1", test: "test1" },
{ id: "id1", test: "test2", test2: "test4", test3: "test3" },
{ id: "id2", test: "test3" },
{ id: "id1", test2: "test4" },
{ id: "id1", test2: "test5" },
{ id: "id1", test2: "test6" },
{ id: "id1", test4: "test7" },
{ id: "id1", test5: "test8" },
];
type ResultType = { [key: string]: string | string[] };
const b = a.reduce((acc, curr) => {
const existingObj = acc.find((obj) => obj.id === curr.id);
if (!existingObj) {
return [...acc, { ...curr }];
}
Object.entries(curr).forEach(([key, value]) => {
if (key !== "id") {
const preVal = existingObj[key];
if (preVal === undefined) {
existingObj[key] = value;
} else {
existingObj[key] = Array.isArray(preVal)
? [...preVal, value]
: [preVal, value];
}
}
});
return acc;
}, [] as ResultType[]);
// Output
[
{
id: "id1",
test: ["test1", "test2"],
test2: ["test4", "test4", "test5", "test6"],
test3: "test3",
test4: "test7",
test5: "test8",
},
{
id: "id2",
test: "test3",
},
];
Brief explanation
TypeScript allows you to manipulate arrays of objects flexibly.
Here, I will explain how to merge objects with the same key based on an arbitrary property from an array of objects and generate a new array of objects.
First, define the object type. Here, the id property is required, and other properties are strings.
type ObjectType = {
[key: string]: string;
} & { id: string };
Next, prepare an array of type ObjectType as sample data.
const a: ObjectType[] = [
{ id: "id1", test: "test1" },
{ id: "id1", test: "test2", test2: "test4", test3: "test3" },
{ id: "id2", test: "test3" },
{ id: "id1", test2: "test4" },
{ id: "id1", test2: "test5" },
{ id: "id1", test2: "test6" },
{ id: "id1", test4: "test7" },
{ id: "id1", test5: "test8" },
];
Define the type for the merged object. The property values will be either a string or an array of strings.
type ResultType = { [key: string]: string | string[] };
Now, let's merge the array using the reduce method.
const b = a.reduce((acc, curr) => {
const existingObj = acc.find((obj) => obj.id === curr.id);
if (!existingObj) {
return [...acc, { ...curr }];
}
Object.entries(curr).forEach(([key, value]) => {
if (key !== "id") {
const preVal = existingObj[key];
if (preVal === undefined) {
existingObj[key] = value;
} else {
existingObj[key] = Array.isArray(preVal)
? [...preVal, value]
: [preVal, value];
}
}
});
return acc;
}, [] as ResultType[]);
In the reduce method's callback function, first use the find method to check if an object with the same id as the current object (curr) already exists in the result array (acc).
If it doesn't exist, the current object is added to the result array as a new object.
If it does exist, iterate through the current object's properties using the Object.entries method.
Since the id property serves as the identifier in this case, it will always exist, and we don't want it to be turned into an array, so we exclude it.
For other properties, check if they exist in the existing object.
If not, add the property and value directly to the object.
If they do exist, check if the property value is already an array. If it is an array, add the new value using the spread syntax. If it's not an array, create a new array containing both values.
Finally, the reduce method returns the array of merged objects.
In this way, you can use TypeScript to merge an array of objects using an arbitrary property as a key.
If there are multiple objects with the same key, property values are handled as arrays; for a single value, they are handled as strings.
Conclusion
In this post, I shared some useful tips regarding TypeScript.
I feel that there are quite a lot of useful things out there in the world.
Thank you for reading this far.
Discussion