sens_vk
sens_vk

Reputation: 231

How to type define destructured arrow function expression arguments?

I am trying to do a little function that capitalizes the first letter of a word but typescript is giving me grief and I am not sure how to type define it.

Can you please help me type define this function:

const capitalize = ([firstLetter, ...rest]) => firstLetter.toUpperCase() + rest.join('')

Upvotes: 0

Views: 162

Answers (1)

Orelsanpls
Orelsanpls

Reputation: 23545

As @Bergi rightfully pointed out is that string is not an array.

So either you wish the user to call your method like :

playground

const capitalize = ([
  firstLetter,
  ...rest
]: string[]): string => firstLetter.toUpperCase() + rest.join('');

console.log(capitalize('my string'.split('')));

Either you use an other way to capitalize.

playground

const capitalize = (str: string): string => str.length ? str.substr(0, 1).toUpperCase() + str.substr(1) : '';

console.log(capitalize('my string'));

Upvotes: 1

Related Questions