How to declare a generic function in TypeScript to have only one property of an object T to be of a specific type?
When working with TypeScript, there may be situations where you need to declare a generic function that ensures only one property of an object is of a specific type. In this blog post, we will explore two solutions to achieve this.
Solution 1: Using mapped types
One way to declare a generic function with a specific property type is by using mapped types. Mapped types allow you to create new types based on existing ones by transforming each property in the type.
Here’s an example of how you can use mapped types to declare a generic function:
type SpecificProperty = {
[P in keyof T]: P extends K ? V : T[P];
};
function setSpecificProperty(obj: T, key: K, value: V): SpecificProperty {
return {
...obj,
[key]: value,
};
}
// Usage
const obj = { name: 'John', age: 25 };
const newObj = setSpecificProperty(obj, 'age', '30');
console.log(newObj); // Output: { name: 'John', age: '30' }
In this example, the SpecificProperty
type is defined using a mapped type. The setSpecificProperty
function takes an object, a key, and a value, and returns a new object with the specified property set to the given value.
Solution 2: Using a conditional type
Another approach to declare a generic function with a specific property type is by using a conditional type. Conditional types allow you to conditionally choose types based on a condition.
Here’s an example of how you can use a conditional type to declare a generic function:
type SetSpecificProperty = T extends infer O
? O extends object
? Pick> & { [P in K]: V }
: never
: never;
function setSpecificProperty(obj: T, key: K, value: V): SetSpecificProperty {
return {
...obj,
[key]: value,
};
}
// Usage
const obj = { name: 'John', age: 25 };
const newObj = setSpecificProperty(obj, 'age', '30');
console.log(newObj); // Output: { name: 'John', age: '30' }
In this example, the SetSpecificProperty
type is defined using a conditional type. The setSpecificProperty
function takes an object, a key, and a value, and returns a new object with the specified property set to the given value. The conditional type ensures that the function only works with objects.
Both solutions provide a way to declare a generic function in TypeScript that ensures only one property of an object is of a specific type. Choose the solution that best fits your use case and enjoy the benefits of type safety in your code!
Leave a Reply