What does it mean in typescript: SomeInterface['someKey'][string]

Viewed 41

The data type which function will return SomeInterface['someKey'][string], what does it mean? How the actual data instance look like? Is this an object? An array?

export const getSomething = (param: string): SomeInterface['someKey'][string] => { 
... 
}
1 Answers

Given a non-nullish type T and key-like type K which is a key of T (or a union of such key types), the type T[K] is an indexed access type representing the type of value at that property key (or a union of those property value types).

Or, in other words, if T is the type of a value t, and K is the type of a value K, then T[K] is the type of t[k].

For example:

let s = "hello"; // let s: string;
const l = "length"; // const l: "length"
const n = s[l]; // const n: number;
type N = string["length"]; // type N = number;

So s is of type string, and l is of type "length" (a string literal type), and s[l] is of type number. That means the type string["length"] is the same as number.


Back to your question: the type SomeInterface['someKey'][string] is therefore the type you'd get if you took a value of type SomeInterface (call it si), and index into it with a key of type "someKey" (so, si.someKey), and then index index into that with a key of type string (so, si.someKey.xyz assuming xyz is a key of si.someKey). Something like this:

function foo(si: SomeInterface) {
  const sis = si.someKey; // SomeInterface['someKey']
  const k = Object.keys(sis)[0]; // string
  return sis[k]; // SomeInterface['someKey'][string];
}

Here, the function foo() will return a value of type SomeInterface['someKey'][string].


Now, as for what type that actually is, that depends entirely on the definition of SomeInterface. Apparently it has a key named someKey, and the property at that key has a string index signature.

If, for example, it looks like this:

interface SomeInterface {
  someKey: {
    [k: string]: Date
  }
  someOtherKey: number;
}

then SomeInterface["someKey"][string] is Date.

Playground link to code

Related