mangokitty
mangokitty

Reputation: 2329

How to specify an array of characters in TypeScript

I need to pass this array into my function using Typescript:

  const message = [ 'c', 'a', 'k', 'e', ' ',
                'p', 'o', 'u', 'n', 'd', ' ',
                's', 't', 'e', 'a', 'l' ];

As TypeScript doesn't have a type for a fixed length character, I'm not sure what is the best way to pass in the array to my function.

Right now I'm calling it like this but I want to do it in a better way

function reverseWords(wordArray :any[]): any[]{

}

I also tried using generics to make sure the input and output were the same but got the error "Type 'string' is not assignable to type 'T'"

function reverseWords<T>(wordArray: Array<T>): Array<T> {
  return ["c", "a", "k", "e"];
}

Thanks so much for any guidance on this, I'm clearly new to Type Script.

Upvotes: 0

Views: 2911

Answers (1)

&#196;lskar
&#196;lskar

Reputation: 2577

You could use an enum to do it, but if you don't want the run-time code or the indirection provided by enums then another way you could do this is define a custom string type union for your characters:

type Char = 'c' | 'a' | 'k' | 'e' | ' ' | 'p' | 'o' | 'u' | 'n' | 'd' | ' ' | 's' | 't' | 'e' | 'a' | 'l';

const messageOk: Char[] = [ 'c', 'a', 'k', 'e', ' ',
            'p', 'o', 'u', 'n', 'd', ' ',
            's', 't', 'e', 'a', 'l' ]; // OK!

const messageNotOk: Char[] = [ 'c', 'a', 'k', 'e', ' ',
            'p', 'o', 'u', 'n', 'd', ' ',
            's', 't', 'e', 'a', 'l', 'x' ]; // Not OK! x does not exist on type Char

function reverseWords(wordArray : Char[]): Char[] {
   ...
}

This is almost like an enum in that each string in this union is a type on its own and is only assignable to that string.

Upvotes: 2

Related Questions