简体   繁体   English

TypeScript-确保数组具有字符串文字中的所有值

[英]TypeScript - ensure array has all values that are in string literal

Is it possible to type an array to ensure it has at the exact values that exist in a string literal? 是否可以键入数组以确保它具有字符串文字中存在的确切值? (not necessarily in the same order) (不一定是相同的顺序)

My attempt below warns if an incorrect value is passed, but not if one is missing. 如果传递了不正确的值,我在下面的尝试会发出警告,但是如果缺少一个,则不会发出警告。

Is this possible? 这可能吗?

export type IconProps = {
  name: 'arrow-up' | 'arrow-down' | 'chevron-up' | 'chevron-down'
} & React.SVGAttributes<SVGElement>


type IconArr = IconProps['name'][]
const arr: IconArr = ['arrow-up', 'arrow-down', 'chevron-up'] // <- 😢 should complain that 'chevron-down' missing.

Why not just reverse the types: 为什么不反转类型:

 const arr = <const> ['arrow-up', 'arrow-down', 'chevron-up'];

 export type IconProps = {
   name: (typeof arr)[number]
 } & React.SVGAttributes<SVGElement>

<const> ensures that the tyepof arr is a tuple type, and not a string[] . <const>确保tyepof arr是元组类型,而不是string[]

you can just try this:- 您可以尝试以下方法:

const arr = ['arrow-up', 'arrow-down', 'chevron-up'] const arr = ['向上箭头','向下箭头','雪佛龙向上']

console.log(typeof arr); console.log(typeof arr);

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

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