What do you think about a C# 6 like nameof() expression for

Augusto Moura augusto.borgesm at gmail.com
Fri Jun 14 21:44:53 UTC 2019


Fri, 14 jun 2019 - 18:29, Jordan Harband <ljharb at gmail.com> wrote:
>
> `nameof whatever` → `Object.keys({ whatever })[0]`, but I'm a bit confused why it'd be better to type `nameof foo` in code, rather than `'foo'` - if you change `foo` to `bar`, you have to change both of them anyways.
>

Exactly, if you already have the name of the property beforehand in
design time why not write it as a string literal

Again, the only justifiable use case is refactoring tools, but even
today that can be arranged with static code analysis

You can safe guard a string literal to be a property of a type in
Typescript with a bit of handwork
``` ts
interface Options {
  userName?: string;
}

// If you change the property in the interface without changing here, Typescript
// will raise a error informing that 'userName' is not a valid key of Options
const userNameKey: keyof Options = 'userName';

if (options.userName === undefined) {
  throw new ParamNullError(userNameKey);
}
```

-- 
Atenciosamente,

Augusto Borges de Moura


More information about the es-discuss mailing list