gr2m / initials

extract initials from and add initials to names
https://gr2m.github.io/initials
MIT License
44 stars 14 forks source link

More intelligent TypeScript return type #81

Closed ikornienko closed 2 years ago

ikornienko commented 4 years ago

Problem

Currently it has

type NameOrNames = string | string[];

function initials(nameOrNames: NameOrNames, options?: Options): string | string[];

which adds additional pain to the user who has to deal with the fact that

const myInitials: string = initials('John Doe');

won't compile, besides documentation explicitly saying that the result will be JD (i.e. string).

Possible way to improve typings

type NameOrNames = string | string[];

function initials<T extends NameOrNames>(nameOrNames: T, options?: Options): T;

In this case if array is passed as a first argument, then function returns an array. And if it's just a string then its return type also is just a string.

gr2m commented 4 years ago

I think a better approach would be a function type override

function initials(nameOrNames: string, options?: Options): string;
function initials(nameOrNames: string[], options?: Options): string[];

Not sure if that's the exact syntaxt, but I think that would work better and does not require a type parameter

ikornienko commented 4 years ago

Function overload would be ideal! While not being a TS expert, I wasn't aware that TS supports it, but it's indeed there (docs). Definitely better to make those two function signatures defined explicitly.

github-actions[bot] commented 2 years ago

:tada: This issue has been resolved in version 3.1.2 :tada:

The release is available on:

Your semantic-release bot :package::rocket: