Reputation: 5825
I want to define an object O
that is generic over some type argument T extends string
in such a way that the object O
always has a key with the value of T
.
type O<T extends string> = { [t in T]: string };
function f<T extends string>(t: T, o: O<T>) {
const x = o[t];
return x === "hello";
}
let s = f("a", { a: "" })
if (s === "Hello") {
}
This is what I tried but it doesn't actually work since O[T]
is not inferred to string. This means that the last if
has an error because TypeScript the comparison will always be false
.
Upvotes: 0
Views: 63
Reputation: 249476
O[T]
will not directly show up as string
but it will behave as string
for all intents and purposes:
type O<T extends string> = { [t in T]: string };
function f<T extends string>(t: T, o: O<T>) {
let x = o[t];
let s: string = x; // assignable to string
x = "S" // string can be assigned to it
return x;
}
let s: string = f("a", {a: ""}) // outside it is string
Upvotes: 1