Home > other >  Access type of a field of an object type using dot notation
Access type of a field of an object type using dot notation

Time:10-28

Given an object type, one can access the type of one of the fields using the bracket-string notation. Why isn’t it possible to use the dot notation as well, like in Javascript? Does it conflict with something else? I feel like I am missing something obvious.

type Foo = {value: number | string};
type Bar = Foo["value"]; // Works, Bar is number | string
type Baz = Foo.value;    // Error

The error message says something about namespaces, but even if there is a namespace named Foo, then Foo.value refers to a value and not a type, so it still doesn’t seem ambiguous.

CodePudding user response:

I also asked myself that, when I first encountered this feature. The feature in question is called "Indexed Access Types" and if you look into the documentation it's clear why TypeScript chose this syntax over the dot notation: It is much flexible. Consider these examples:

type Person = { age: number; name: string; alive: boolean };
type I1 = Person["age" | "name"]; 
// I guess here we could do: type I1 = Person.age | Person.name; 

type I2 = Person[keyof Person];  
 
type AliveOrName = "alive" | "name";
type I3 = Person[AliveOrName];

As noted in the comment the first example could easily be rewritten with the dot notation, but the other examples are clearer with the array index notation.

Maybe TypeScript could add the suggested dot syntax for simple cases as syntactic sugar, but I'm not sure everyone would like this as then there are multiple notations for the same feature.

CodePudding user response:

with the following code:

type Baz = Foo.value;

If you want to use it, you must define value of value variable.

Because, Object properties are equivalent to key-value pairs. Property keys are either strings or symbols.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#properties

  • Related