gpt4 book ai didi

Typescript:排除 不排除我的类型

转载 作者:行者123 更新时间:2023-12-03 08:56:09 24 4
gpt4 key购买 nike

我构建了一个名为 compact 的函数,该函数的作用是删除数组中的所有虚假值。

这是 compactjavascript 实现:

function compact(arr) {
return arr.filter(Boolean);
}

const MyData = [0, 1, null, 2, undefined, ''];

console.log(compact(MyData))
// => [1, 2]

这是 compactTypescript 打字部分:

type Falsy = false | null | 0 | '' | undefined;

type Compact<T extends any[]> = Exclude<T[number], Falsy>;

// some correct test
type MyData = [0, 1, null, 2, undefined, ''];

type MyDataWithoutFalsy = Compact<MyData>
// => type MyDataWithoutFalsy = 1 | 2

enter image description here

现在,奇怪的部分来了,当我将它与compact代码连接起来时,它实际上并没有工作:

function compact<T extends any[]>(arr: T): Compact<T> {
return arr.filter(Boolean) as Compact<T>;
}

let MyDataWithoutFalsy = compact([0, 1, null, 2, undefined, '']);
// => let MyDataWithoutFalsy: string | number, but it should be `number` only, because empty string should be excluded.

它应该只是数字,因为应该排除空字符串。

enter image description here

最佳答案

问题不在于 Exclude,问题在于对于 "" (不仅仅是这个字符串文字,对于任何字符串文字) typescript 通常不会保留字符串文字类型,但它宁愿将其扩展为 string 除非我们给它一个保留文字类型的理由。

为了向编译器提示您需要文字类型,必须将文字分配给受文字基类型约束的泛型类型参数:

function compact<V extends (string | undefined | boolean | object | number | null), T extends V[]>(arr: T & V[]): Compact<T> {
return arr.filter(Boolean) as Compact<T>;
}

let MyDataWithoutFalsy = compact([0, 1, null, 2, undefined, '']); // number


type Falsy = false | null | 0 | '' | undefined;

type Compact<T extends any[]> = Exclude<T[number], Falsy>;

请注意,这确实意味着 compact 不会真正可用,除非您以保留文字类型的方式构造数组(例如 '')。

function compact<V extends (string | undefined | boolean | object | number | null), T extends V[]>(arr: T & V[]): Compact<T> {
return arr.filter(Boolean) as Compact<T>;
}
function literalArray<V extends (string | undefined | boolean | object | number | null)>(arr: V[]): V[] {
return arr.filter(Boolean);
}
let arr = literalArray([0, 1, null, 2, undefined, ''])
let MyDataWithoutFalsy = compact(arr); // 1| 2 ... beacuse resons

关于Typescript:排除<T, K> 不排除我的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55204621/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com