DEV Community

Discussion on: The types in TypeScript

peerreynders profile image
peerreynders

Inferring the return type of a function is not an "accidental byproduct", but actually the result of your arguments. Depending on what you do with those arguments, the type of the return.

the value I see in inferred return types is that you can change the implementation and get the correct "new type" without having to go and change the output type every time you do this.

So again the return type is a consequence of the implementation.

When you "think in/develop with types" the implementation is a consequence of the desired type - i.e. the relationship it flipped.

Consider this scenario

type MyType = {
  count: number;
  average: number;
};

function fn(values: number[]) {
  const count = values.length;
  const average =
    count > 0 ? values.reduce((sum, value) => sum + value, 0) / count : NaN;

  return {
    count,
    average,
  };
}
Enter fullscreen mode Exit fullscreen mode

We find that MyType also needs total.

type MyType = {
  count: number;
  average: number;
  total: number;
};

function fn(values: number[]) {
  const count = values.length;
  const average =
    count > 0 ? values.reduce((sum, value) => sum + value, 0) / count : NaN;

  return {
    count,
    average,
  };
}
Enter fullscreen mode Exit fullscreen mode

No error that the result from fn is no longer sufficient. If we are lucky somewhere the result will be delivered to an explicitly typed binding, alerting us to the problem with the function (or any others that produce a similar result).

With an explicit return type compilation will identify all the functions that no longer produce the correct type.

type MyType = {
  count: number;
  average: number;
  total: number;
};

function fn(values: number[]): MyType {
  const count = values.length;
  const average =
    count > 0 ? values.reduce((sum, value) => sum + value, 0) / count : NaN;

  // Property 'total' is missing in type '{ count: number; average: number; }' but required in type 'MyType'.
  return {
    count,
    average,
  };
}
Enter fullscreen mode Exit fullscreen mode

i.e. the type is changed before the implementation(s).

A capability in terms of value-orientation:

  • What is the shape of the data I need
  • What is that shape of the data I have
  • How do I transform what I have into what I need.

i.e. contracts (constraints) first, implementation last.

Aside Why type-first development matters

It looks like the intent of that code is to take a number argument and return "100" or 1, so yes, that the correct type for its output.

My intent was to simulate a defect (which perhaps would only be detected at an explicitly typed site of use), i.e. the intended return type should either have been string or number - not string | number.

This way you're effectively doing "JS with types" instead of writing a plethora of types just to write "more TS".

JS Doc TS with (hand written) declaration files is "Typed JS". There's a clean separation between "type space" (TypeScript types) and "value space" (the JS implementation).

The entire point of the index.d.ts and internal.d.ts files is to explicitly formulate a constrained set of types that are expected to be encountered (without having to formulate them "ad hoc").

The problem is that using JS Doc TS well (as far as I can tell) requires a higher level of TS competence (especially its "typing language") than writing TS destined for transpilation.

and many other utils to infer types from static values.

Those features can help to cut down on verbosity and emerge as TS tries to tease whatever type information it can out of the JS value space to make it available in type space. But in terms of design, types are typically formulated before the implementations and defined in type space (rather than extracted from value space).

Type space derived from value space is like drafting a blueprint after the house has already been built.

Thread Thread
lukeshiru profile image
Luke Shiru

I think your approach is heavily inspired by how folks solved stuff with classes. What I mean by this is that you think that types are like the design/blueprint of how everything should look like, way before you even start working on the implementation. Meanwhile, I prefer to use types in TypeScript as a tool to know what the type of something will be while I work on it, not before.

Considering your scenario, you could get that MyType from the function if you want:

function fn(values: number[]) {
    const count = values.length;
    const average =
        count > 0 ? values.reduce((sum, value) => sum + value, 0) / count : NaN;

    return {
        count,
        average,
    };
}

type MyType = ReturnType<typeof fn>;
Enter fullscreen mode Exit fullscreen mode

So if you change the implementation, the type adjusts to that. Basically, you make TS work for JS instead of the other way around. With this approach, let's say we have other two functions that take the output of fn as input:

const doubleCount = ({ count }: MyType) => count * 2;
const doubleAverage = ({ average }: MyType) => average * 2;
Enter fullscreen mode Exit fullscreen mode

With your approach, if let's say count changes and now is a string instead of a number, we need to first change the type in MyType, then change the implementation in fn, then resolve the issues in doubleCount. With my approach you only change the implementation, and then get errors were is relevant (like doubleCount). No need to update types.

My intent was to simulate a defect (which perhaps would only be detected at an explicitly typed site of use), i.e. the intended return type should either have been string or number - not string | number.

If you want your function to return one or the other, and you're returning both, you'll know it as soon as you try to use it in a place where you're expecting a single type and you get both:

const fn = (arg: number) => (arg > 50 ? "100" : 1);

const double = (number: number) => number * 2;

double(fn(10)); // Error here: Argument of type 'string | number' is not assignable to parameter of type 'number'
Enter fullscreen mode Exit fullscreen mode

The difference is that now I can figure out if I want fn to return a number or if I want to handle the case where fn returns a string:

const fn = (arg: number) => (arg > 50 ? 100 : 1);

// or
const parseNumber = (numberOrString: number | string) =>
    typeof numberOrString === "string"
        ? parseInt(numberOrString, 10)
        : numberOrString;
const double = (number: number) => number * 2;

double(parseNumber(fn(10)));
Enter fullscreen mode Exit fullscreen mode

But in terms of design, types are typically formulated before the implementations and defined in type space (rather than extracted from value space).

I agree to a certain degree, but as I stated before, the types you "design first" should be there just to help out with the JS part, not for the sake of types. Generally, you need to type arguments to let others and yourself in the future know what a function takes, but the output should be defined by the implementation. You don't lose any safety and you still gain lots of flexibility.

Type space derived from value space is like drafting a blueprint after the house has already been built.

With this I disagree again, I feel a closer analogy would be that types derived from implementation are like having a map of your code, that updates automatically as you change it. If a mountain comes out of nowhere, you'll know. From my point of view, the usefulness of TypeScript comes when you augment JavaScript with it, not when you have to code in JavaScript to accommodate TypeScript types.

I understand that for you is valuable to make a "design first, and implement after", but I prefer to use types to help me out while I implement. More often than not, when you start coding the implementation you'll figure out that you might need changes in the design. With my approach, I just make those changes and types let me know if that change had any negative effect, but with yours, you need to go back to the types first, resolve the change there, and just then work on the implementation.

Just to clarify, is not just a whim or anything like that. I originally started using TypeScript because it had classes when JS didn't, and I was able to write code in a similar manner to C++ but on the web, so I get where you're coming from. Nowadays, after years of working with this language, not only did I stop using classes altogether, but also after working in lots of projects and companies with lots of people I found that the best use for TS in WebDevs is the one I suggest:

  • Is easier to grasp for people not familiar with TS.
  • Is easier to maintain and update.
  • Is equally safe, if you avoid any, non-null assertion and all those "I'm smarter than the language" kinds of things.
  • Is faster because we focus on the implementation, and the types are derived from that.
Thread Thread
peerreynders profile image
peerreynders • Edited on

I think your approach is heavily inspired by how folks solved stuff with classes.

Design by Contract is attributed to Bertrand Meyer in connection with the Eiffel OOPL (1986) but the "type first" notion appears elsewhere like in Clojure's "thinking in data, modeling in data, and working in data" which is most definitely not OO.

And the idea of "function types as contracts" is up-to-date - 3.7.1 Types and Contracts.

Explicit types serve as deliberate "check points" during type checking/linting.

Is faster because we focus on the implementation, and the types are derived from that.

Expedience is always fielded as the primary motivation for "implementation first, contract last" approaches. But more often than not, contract last approaches save you time in the short term but create problems (that could be avoided by actively managing your types) in the long term (TTIS - Time-To-Initial-Success).

To some degree it's like saying "I know that JSDoc annotations are helpful for maintenance but keeping them in sync with the code slows me down so it's not worth it". Types are part of the application's specification that are supposed make it easier to reason about the code, so it helps if they are not buried somewhere in the implementation.

I guess the lesson here is: just because TypeScript is being used doesn't actually reveal whether the potential of types is being leveraged to maximum effect (to the extend that is even possible in TypeScript).

Aside: