Max Shaw
Max Shaw

Reputation: 11

Is there a way to return a type that is one item in an array

I'm trying to define a typescript function that accepts an array of strings and then returns a string. The string is guaranteed to be one of the options in the array. I want the return type to be "string1" | "string2" | "string3" rather than just a generic string.

This way the person who calls the function can use typescript on the returned value.

Upvotes: 0

Views: 69

Answers (2)

MBB
MBB

Reputation: 1685

From the problem definition it looks like you are trying to convert the array/tuple of strings into union-type. One of the ways is to use the as const to achieve this which is available from version 3.4. Below is the sample code -

const array = ['x', 'y', 'z'] as const; 
type UnionType = typeof array[number]; // type "x" | "y" | "z"

const func = (input: typeof array): UnionType => {
  return 'x';
};

console.log(func(['x', 'y', 'z']));

Upvotes: 1

Seaworn
Seaworn

Reputation: 557

Use a union type: type myType = "string1" | "string2" | "string3"; That should do it

Upvotes: 0

Related Questions