简体   繁体   English

TypeScript:返回输入字符串数组的文字值的联合?

[英]TypeScript: return a union of the input string array's literal values?

Can I type a function such that it takes a string[] and the output is a string union?我可以输入一个 function 以便它需要一个string[]并且 output 是一个字符串联合吗?

For example, given this function:例如,给定这个 function:

function myfn(strs: string[]) {
  return strs[0];
}

If I call it like:如果我这样称呼它:

myfn(['a', 'b', 'c']) // => return type is: 'a' | 'b' | 'c'

Is this possible in TypeScript?这在 TypeScript 中是否可行?

You can add generic parameter to describe the array item, typescript will be able to infer it from provided value:您可以添加通用参数来描述数组项,typescript 将能够从提供的值推断它:

function myfn<T extends string>(strs: T[]) {
  return strs[0];
}

const result = myfn(['a', 'b', 'c']) // "a" | "b" | "c"

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeScript:从字符串联合文字数组类型,不允许数组中存在任何冗余值 - TypeScript: from a string union literal array type, disallow any redundant values from existing in the array 打字稿字符串文字联合类型 - Typescript string literal union type Typescript 从 object 中的数组创建字符串文字联合类型 - Typescript create string literal union type from array in object 另一个联合类型中的打字稿联合字符串文字 - Typescript union string literal in another union type Map 作为输入类型和属性值列表的联合的返回类型,来自 Typescript 中的数组 - Map a return type as the union of an input type and a list of property values from an array in Typescript typescript - 返回一个 object 键等于输入字符串文字 - typescript - return an object with key equals to an input string literal 打字稿:来自枚举的字符串文字联合类型 - Typescript: string literal union type from enum 有没有办法在 Typescript 中声明一个连续的字符串文字联合 - Is there a way to declare a successive string literal union in Typescript Typescript:typeof 的 output 是否存在字符串文字类型的联合? - Typescript: Is there a union of string literal types for the output of typeof? Typescript 具有联合排列但没有重复的字符串文字 - Typescript string literal with permutations of union but no repetitions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM