0

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.

2
  • 2
    Is there anything wrong with writing string[] as the type? Commented Oct 23, 2019 at 17:18
  • That works, must have over complicated it by discarding String from reading Typescript's definition of a string. Thank you. Commented Oct 23, 2019 at 17:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.