David Gomes
David Gomes

Reputation: 5825

Use a generic string as the key of an object

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.

TypeScript Playground Link

Upvotes: 0

Views: 63

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions