[英]TypeScript - ensure array has all values that are in string literal
是否可以鍵入數組以確保它具有字符串文字中存在的確切值? (不一定是相同的順序)
如果傳遞了不正確的值,我在下面的嘗試會發出警告,但是如果缺少一個,則不會發出警告。
這可能嗎?
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.
為什么不反轉類型:
const arr = <const> ['arrow-up', 'arrow-down', 'chevron-up'];
export type IconProps = {
name: (typeof arr)[number]
} & React.SVGAttributes<SVGElement>
<const>
確保tyepof arr
是元組類型,而不是string[]
。
您可以嘗試以下方法:
const arr = ['向上箭頭','向下箭頭','雪佛龍向上']
console.log(typeof arr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.