繁体   English   中英

可以根据类型参数覆盖的打字稿类型

[英]Typescript types that can be overwritten based on type arguments

我试图找出告诉打字稿编译器返回T | null的函数的最佳方法。 在某些情况下, T | null肯定是T

也许我正在考虑这个错误,在这种情况下我也对新想法持开放态度,这里是片段:

type ValueOrNull<T, N> = N extends false ? T | null : T;

export function getCookie<T = any, N = false>(name: string): ValueOrNull<T, N> {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));

  if (match) {
    const [, , value] = match;

    return parseCookieValue(value) as T;
  }

  return null;
}

我的想法是,如果我可以按如下方式调用该函数: getCookie<TMyCookie, true>("my_cookie")打字稿会知道我确定 cookie 会在那里,并且该函数不会返回 null。 例如成功登录后。

N extends false ? 感觉不对,但N === false不起作用。

编译器错误是Type 'null' is not assignable to type 'ValueOrNull<T, N>'.ts(2322)

非常感谢

您可以通过函数重载和第二个参数轻松地做到这一点; 当(不可避免地)程序员“知道”cookie存在但它不存在时,这也可以让您构建一个有用的解释性错误:

export function getCookie<T>(name: string, required: true): T;
export function getCookie<T>(name: string, required?: false): T | null;
export function getCookie<T>(name: string, required?: boolean): T | null {
    const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));

    if (match) {
        const [, , value] = match;
        // You'll want to put your `parseCookingvalue` back here,
        // the `as any as T` is just because we don't have that
        // function available to use in the question.
        return /*parseCookieValue(value)*/ value as any as T;
    } else if (required) {
        throw new Error(`Required cookie "${name}" was not found`);
    }
    return null;
}

const a = getCookie<string>("a", true);
//    ^? −−−− type is string
const b = getCookie<string>("b", false);
//    ^? −−−− type is string | null

游乐场链接


不过,这里有一个替代方案:您可以让getCookie相当简单,并拥有一个通用类型断言函数,您可以在任何地方使用该函数,您可以返回可能为nullundefined并且您“知道”它不是nullundefined的东西:

export function getCookie<T>(name: string): T | null {
    const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));

    if (match) {
        const [, , value] = match;
        // You'll want to put your `parseCookingvalue` back here,
        // the `as any as T` is just because we don't have that
        // function available to use in the question.
        return /*parseCookieValue(value)*/ value as any as T;
    }
    return null;
}

export function assertIsNotNullish<T>(value: T | null | undefined): asserts value is T {
    if (value == null) {
        throw new Error(`Expected non-nullish value, got ${value}`);
    }
}

const a = getCookie<string>("a");
assertIsNotNullish(a);
console.log(a);
//          ^? −−−− type is string
const b = getCookie<string>("b");
console.log(b);
//          ^? −−−− type is string | null

游乐场链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM