Here I have a question that has two parts:
- I am curious to know if there is a way in TypeScript where it's possible to restrict a generic to be a specific literal type. What I mean is something like
. The closest approach I found was usingfunction foo<T is a string literal>(...)
function foo<T extends string>
, but this still allows unions of string literals and the general "string" type for T. - If achieving this behavior is not feasible in TypeScript 2.1, would it be logical from a design standpoint to introduce such functionality?
The context behind my query revolves around defining a curried function called prop
, demonstrated here:
function prop<K extends string, U>(name: K): <T extends { [P in K]: U }>(obj: T) => T[K] {
return (obj) => obj[name];
}
prop<'name', number>("name")({
name: 3
})
In this example scenario, everything functions as intended when K
is a string literal, but the function's type checking faces issues when K
is just a plain string
.
This might seem somewhat forced; please keep in mind my aim isn't necessarily to tackle a practical issue (though it could do so), but more so to explore TypeScript's type system.
Appreciate your insights!