TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Support type-checking of computed properties for constants and Symbols

Open IgorMinar opened this issue 11 years ago • 34 comments

On Angular we are considering using ES6 computed prototype methods as part of Angular’s component api but we realized that typescript doesn’t allow us to express this in a type-safe way.

I’m wondering if this is a feature that could be added to typescript or if there is a fundamental issue that would prevent typescript from supporting this. Example:

{Component, onInit, OnInit} from ‘angular2/core';

@Component({
  selector: 'my-component'
})
class MyComponent implements OnInit {
  [onInit](param1, param2){ return something; }
}

Where onInit is a const string or ES Symbol, and OnInit is an interface with the signature of the [onInit] method. onInit is a an optional life-cycle hook that Angular will call if the component has this property name.

The reason why we find this api style attractive is that it removes the possibility of name-collisions, which means that we are free to add support for more hooks in the future without affecting any existing components.

PS: ES Observables are already using Symbols to define the observable interface, so this feature would allow creation of Observable interface. I expect more libs will want to take advantage of this api style as computed property and Symbol support becomes better.

Related issue: #4653

IgorMinar avatar Nov 09 '15 23:11 IgorMinar

@isiahmeadows Could you elaborate on point 1, and offer a revised suggestion with respect to both points?

axefrog avatar Apr 15 '17 04:04 axefrog

@axefrog Here's one:

const sym = Symbol("foo")
function getFoo() { return sym }
const foo = getFoo() // Easily proven

And here's how I'd change it:


Eligible values are one the following:

  1. A direct Symbol("literal") or Symbol() call.
  2. A well known symbol.
  3. An expression result that's 1 or 2 (implicitly an alias).
  4. An expression result returning an eligible symbol name's value
// Accepted
Symbol("foo")
Symbol()
const foo = Symbol("foo"); (() => foo)()

// Rejected
Symbol("fo"+"o")
Symbol(ident)
(() => Symbol("foo"))()

Eligible bindings are one of the following

  1. A const binding.
  2. A readonly property within an object tied to a const binding.
  3. A readonly property within an object tied to an object within 2 or 3.
// Accepted
const foo = ...
const ns: {readonly foo: symbol} = ...
const nested: {readonly ns: typeof ns} = ...

// Rejected
let foo = ...
const ns: {foo: symbol} = ...
const nested: {ns: typeof ns} = ...

Eligible symbol names are eligible bindings that return eligible values.

dead-claudia avatar Apr 15 '17 06:04 dead-claudia

This feature would also be helpful when working with React. A minimal example:

import * as React from 'react';
import { ChangeEvent } from 'react';

interface LoginState { username: string; password: string; }

export class Login extends React.Component<{}, LoginState> {
  public state: LoginState = { username: '', password: '' };

  private onChange(event: ChangeEvent<HTMLInputElement>, property: keyof LoginState) {
    this.setState({ [property]: event.target.value });  // this doesn't work!
  }

  public render() {
    return (
      <form>
        <input value={this.state.username}
               onChange={(e) => this.onChange(e, 'username')}/>
        <input type="password"
               value={this.state.password}
               onChange={(e) => this.onChange(e, 'password')}/>
        <input type="submit" value="Login"/>
      </form>
    );
  }
}

Relevant definition of setState:

class Component<P, S> {
    setState<K extends keyof S>(state: Pick<S, K>, callback?: () => any): void;
}

Right now the commented line in onChange does not typecheck. The compiler doesn't realize that a { [k: keyof LoginState]: string } can be assigned to a Pick<LoginState, K extends keyof LoginState>.

We currently bypass this by calling this.setState({ ...this.state, [property]: event.target.value }), but this essentially bypasses the typechecker (e.g. calling this.setState({ ...this.state, foo: 'bar' }) compiles as well). It's also passing more keys than necessary to setState, and making it do unnecessary work.

whatisaphone avatar May 04 '17 19:05 whatisaphone

@johnsoft i am afraid this is a different request and not included in this issue.

mhegazy avatar May 04 '17 19:05 mhegazy

@mhegazy You closed issue #15534 as a dup of this one yesterday :). It seems to me it fits within "type-checking of computed properties for constants".

As far as I can tell (and I could be wrong), #15534 is the root cause of the React issue above. What would be the best way for me to get the above issue on the typescript team's radar?

whatisaphone avatar May 04 '17 20:05 whatisaphone

i see. this issue are about using a computed property whose type is a single literal type, and that is constant. thus the compiler can make assumptions about the name/key of the property. The example in #15534 made it seem like that is what you were looking for.

The setState example makes it clear what you are looking for. What is needed here is to distribute the type over the union in keyof. i.e. { [property]: event.target.value } would have the type { "username": event.target.value } | { "password": event.target.value }. Do not think this is the same issue. if you want to file a new issue or add more details to #15534 we can reopen it.

mhegazy avatar May 04 '17 20:05 mhegazy

Sure, I'll copy my example over to the previous issue.

whatisaphone avatar May 04 '17 21:05 whatisaphone

I would want to warn against this.setState({ ...this.state, [property]: event.target.value }) because it might not do what you expect due to setState's asynchronous nature.

Another workaround which does not change your JavaScript output is

this.setState({ [property]: event.target.value } as { username: string } | { password: string });

jacobrask avatar May 13 '17 19:05 jacobrask

@jacobrask For the above example, setState works well enough, and in addition, setState is called after the mapped property is resolved, so that's not a concern.

dead-claudia avatar May 13 '17 20:05 dead-claudia

@johnsoft Your onChange was slightly incorrect, so the types would likely be incorrectly inferred. If you add a generic so TypeScript can pass through the information that property only carries one property name, it might work better. See if this fixes your issue:

import * as React from 'react';
import { ChangeEvent } from 'react';

interface LoginState { username: string; password: string; }

export class Login extends React.Component<{}, LoginState> {
  public state: LoginState = { username: '', password: '' };

  private onChange<K extends keyof LoginState>(event: ChangeEvent<HTMLInputElement>, property: K) {
    this.setState({ [property]: event.target.value });
  }

  public render() {
    return (
      <form>
        <input value={this.state.username}
               onChange={(e) => this.onChange(e, 'username')}/>
        <input type="password"
               value={this.state.password}
               onChange={(e) => this.onChange(e, 'password')}/>
        <input type="submit" value="Login"/>
      </form>
    );
  }
}

dead-claudia avatar May 13 '17 20:05 dead-claudia

@isiahmeadows Doesn't work, unfortunately.

$ tsc "-v"
Version 2.4.0-dev.20170518
index.tsx(11,19): error TS2345: Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'Pick<LoginState, "username" | "password">'.
  Property 'username' is missing in type '{ [x: string]: string; }'.
index.tsx(11,21): error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.

whatisaphone avatar May 18 '17 17:05 whatisaphone

@johnsoft The way you were doing it before would've been not type-safe across fields, which is why I suggested the change. I didn't expect it'd solve your problem completely, but it'll make it easier to catch errors (and hit this bug).

dead-claudia avatar May 19 '17 08:05 dead-claudia

@isiahmeadows Right, I get it. It would matter in the case where username and password were not the same type.

whatisaphone avatar May 19 '17 19:05 whatisaphone

Any update on this? I noticed I still cannot strongly type my non built-in symbol property declarations in 2.6 👎

nbransby avatar Nov 06 '17 13:11 nbransby