是否可以在 Typescript 中定义非空数组类型? [英] Is it possible to define a non empty array type in Typescript?

查看:25
本文介绍了是否可以在 Typescript 中定义非空数组类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我知道永远不会为空的数字列表.是否可以在 Typescript 中定义一个永远不会为空的数组?

I have a list of numbers that I know is never empty. Is it possible to define an array in Typescript that is never empty?

我知道可以使用像 [ number, number ] 这样的元组,但这不起作用,因为我的数组可以是任意大小.

I know that it is possible with tuples like [ number, number ] but this will not work as my array can be any size.

我想我正在寻找的是 NonEmptyArray 类型.

I guess what I am looking for is a NonEmptyArray<number> type.

它存在吗?:)

推荐答案

一个功能请求,允许您只检查 array.length >0 防止空数组,microsoft/TypeScript#38000,被拒绝因为太复杂了.本质上,您通常不能简单地在 TypeScript 中检查 length 来说服编译器关于给定数字键的属性的可用性.

A feature request for allowing you to just check array.length > 0 to guard against empty arrays, microsoft/TypeScript#38000, was declined as being too complex. Essentially you cannot usually simply check length in TypeScript to convince the compiler about the availability of properties at given numeric keys.

你可以像这样定义一个非空数组类型:

You can define a non-empty array type like this:

type NonEmptyArray<T> = [T, ...T[]];

const okay: NonEmptyArray<number> = [1, 2];
const alsoOkay: NonEmptyArray<number> = [1];
const err: NonEmptyArray<number> = []; // error!

这是由于在 TS 3.0 中添加了对 元组类型中的其余元素.我不确定您的用例是什么......不过,使用这种类型可能比您预期的更烦人:

This is due to support added in TS 3.0 for rest elements in tuple types. I'm not sure what your use case is... It's probably more annoying to use that type than you expect, though:

function needNonEmpty(arr: NonEmptyArray<number>) {}
function needEmpty(arr: []) {}

declare const bar: number[];
needNonEmpty(bar); // error, as expected

if (bar.length > 0) {
    needNonEmpty(bar); // ugh, still error!
}

如果你想让 length 检查工作,你需要使用类似用户定义的类型保护函数的东西,但使用起来仍然很烦人:

If you want a length check to work, you'll need to use something like a user-defined type guard function, but it's still annoying to use:

function isNonEmptyArray<T>(arr: T[]): arr is NonEmptyArray<T> {
    return arr.length > 0;
}

if (isNonEmptyArray(bar)) {
    needNonEmpty(bar); // okay
} else {
    needEmpty(bar); // error!! urgh, do you care?        
} 

无论如何希望有帮助.祝你好运!

Anyway hope that helps. Good luck!

这篇关于是否可以在 Typescript 中定义非空数组类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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