具有最小长度的 TypeScript 数组 [英] TypeScript array with minimum length

查看:34
本文介绍了具有最小长度的 TypeScript 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 TypeScript 中创建只接受具有两个或更多元素的数组的类型?

How can you create a type in TypeScript that only accepts arrays with two or more elements?

needsTwoOrMore(["onlyOne"]) // should have error
needsTwoOrMore(["one", "two"]) // should be allowed
needsTwoOrMore(["one", "two", "three"]) // should also be allowed

推荐答案

这可以通过类似的类型来完成:

This can be accomplished with a type like:

type ArrayTwoOrMore<T> = {
    0: T
    1: T
} & Array<T>

declare function needsTwoOrMore(arg: ArrayTwoOrMore<string>): void

needsTwoOrMore(["onlyOne"]) // has error
needsTwoOrMore(["one", "two"]) // allowed
needsTwoOrMore(["one", "two", "three"]) // also allowed

TypeScript Playground 链接

这篇关于具有最小长度的 TypeScript 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆