Issue
I want to make an createContext
than include a name prefix for returned object, how can tell the user that the return value keys is based on input params, I tried
export function createContext<Name extends string = string>(
name: Name,
): {
[`use${name}Context`]: any;
[`${name}Provider`]: any;
};
export function createContext(name:string){
return {
[`use${name}Context`]:0,
[`${name}Provider`]:0
}
}
But I don't understand the error
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.(1170)
Dose that mean this is impossible ?
Solution
The easiest solution is probably to use a mapped type. Also don't forget to use the uppercase generic type Name
instead of name
.
export function createContext<Name extends string = string>(
name: Name,
): {
[K in `use${Name}Context` | `${Name}Provider`]: any;
};
If you want both properties to have different types, you can intersect multiple mapped types.
export function createContext<Name extends string = string>(
name: Name,
): {
[K in `use${Name}Context`]: number;
} & {
[K in `${Name}Provider`]: string
};
Answered By - Tobias S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.