DEV Community

Discussion on: Some reflections about React and TypeScript

Collapse
 
dance2die profile image
Sung M. Kim • Edited

Is it a norm to let TypeScript infer without specifying types in the code?

Collapse
 
florianrappl profile image
Florian Rappl • Edited

Not sure what you refer to, but yes - use type inference to let types flow. Constrain where necessary, e.g.,

function foo() {
  return {
    a: 'foo',
    b: 'bar',
  };
}

Now here TS infers that

declare function foo(): {
  a: string;
  b: string;
};

but maybe you want that foo always returns something like

interface FooReturn {
  a: 'foo' | 'bar';
  b: string;
  c?: boolean;
}

Now in the free return spec above that is not clear. Even worse, another function taking a parameter of type FooReturn will not work as the return is currently not compatible.

Sure, we could do:

function foo() {
  return {
    a: 'foo' as const,
    b: 'bar' as const,
  };
}

to improve the situation, but in this case decorating the return seems even better, because when we write the function we would already know that another property c is also possible (and its type).

So just use:

function foo(): FooReturn {
  return {
    a: 'foo',
    b: 'bar',
  };
}

Again, it all depends, but once types are given (as in many of the examples above) there is no need to re-specify. This is over-specifying, which should always be avoided (as in any potential refactoring this leads to a wave of unnecessary changes).

Thread Thread
 
dance2die profile image
Sung M. Kim

Thank you Florian for the detailed reply.