简体   繁体   中英

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" "string1" | "string2" | "string3" "string1" | "string2" | "string3" rather than just a generic string .

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

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']));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM