gpt4 book ai didi

typescript 多种类型检查功能

转载 作者:行者123 更新时间:2023-12-02 01:27:58 24 4
gpt4 key购买 nike

背景

我正在使用 typescript 进行类型检查功能。

const checkType = <T>(value: unknown, isTypeFn: (value: unknown) => value is T): T => {
if (!isTypeFn(value)) {
console.error(`${isTypeFn} ${value} does not have correct type`);
throw new Error(`${value} does not have correct type`);
}

return value;
};

const isBoolean = (value: unknown): value is boolean => typeof value === 'boolean';

const isString = (value: unknown): value is string => typeof value === 'string';

const isNumber = (value: unknown): value is number => typeof value === 'number';

const isNull = (value: unknown): value is null => value === null;

我可以像下面这样使用它。

const a = await getNumber() // this should be number
const numA: number = checkType(a, isNumber); // numA is number or throw Error!

问题

我想扩展 checkType 函数,如下所示。

const b = await getNumberOrString();
const bNumOrString: number | string = checkType(b, isNumber, isString);
const bNumOrBoolean: number | boolean = checkType(b, isNumber, isBoolean);
const bStringOrNull: string | null = checkType(b, isString, isNull);

如何改进 checkType 使其像这样工作?

最佳答案

函数checkType将需要一个剩余参数。我们将其称为 isTypeFnsisTypeFns 是一个泛型类型参数 T,它将是带有类型谓词的函数数组。

const checkType = <
T extends ((value: unknown) => value is any)[]
>(value: unknown, ...isTypeFns: T): CheckType<T> => {
if (isTypeFns.some(fn => fn(value))) {
console.error(`${value} does not have correct type`);
throw new Error(`${value} does not have correct type`);
}

return value as CheckType<T>;
};

实现过程非常简单。您只需检查 isTypeFns 中的函数之一是否在给定 value 的情况下返回 true

返回类型再次变得更加棘手。我们需要采用 T推断类型谓词类型的并集。

type CheckType<T extends ((value: unknown) => value is any)[]> = 
T[number] extends ((value: unknown) => value is infer U)
? U
: never

我们使用它作为函数的返回类型。当涉及到实现的 return 语句时,TypeScript 无法理解这种复杂类型。这就是为什么我在那里添加了一个断言。

const b = "b" as number | string;

const bNumOrString = checkType(b, isNumber, isString);
// ^? const bNumOrString: string | number

const bNumOrBoolean = checkType(b, isNumber, isBoolean);
// ^? const bNumOrBoolean: number | boolean

const bStringOrNull = checkType(b, isString, isNull);
// ^? const bStringOrNull: string | null

Playground

关于typescript 多种类型检查功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73996662/

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