如何检查联合类型参数 (T | [string, T][]) 的类型是否为 T 而不是 [string, T][]?

问题描述 投票:0回答:1

我想写一个获取T类型参数的函数 | [string, T][] 并检查参数是否为 T 类型而不是 [string, T][] 类型。 示例:

const example: null | [string, null][] = [['addr1', null], ['addr2', null] ] 
it's type is not null (null is T)

T 不是类,它通常是字符串、数字、字符串[]....

我的第一个实现是:

function isTypeT<T>(response: T | [string,T][], singleResType: new () => T): boolean {
  return response instanceof singleResType;
}

但它要求类型 T 必须有构造函数。
(typeof 函数不会有帮助,因为:

typeof string[] == typeof [string, string[]][] == object

我也想过这个问题:

function isTypeT<T>(response: T | [string, T][], singleRes: T): boolean {
    if (Array.isArray(response) && Array.isArray(singleRes)) {
        return isTypeT(response[0], singleRes[0]);
    } 
     else if (typeof response !== typeof singleRes || Array.isArray(response) || Array.isArray(singleRes)) {
        return false;
    }
    return true;
}

但是每次都传递一个示例对象来检查函数似乎不是一个好的打字稿实现。

因此,如果有人能建议另一种检查类型的方法,我将不胜感激。

javascript typescript typescript-typings typescript-generics typeof
1个回答
0
投票
import { type } from 'arktype'

// not gonna write the checks myself
const stringAnyTupleArray = type([['string', 'any'], '[]']);

const isStringAnyTupleArray = stringAnyTupleArray.allows;
// const isStringAnyTupleArray: (data: unknown) => data is [string, any][]

function isNot<T>(isT: (v: unknown) => v is T) {
  return function isNotT<V>(v: V): v is Exclude<V, T> {
    return !isT(v);
  }
}

const isNotStringAnyTupleArray = isNot(isStringAnyTupleArray);
// const isNotStringAnyTupleArray: <V>(v: V) => v is Exclude<V, [string, any][]>

function foo<T>(t: T | [string, T][]) {
  if (isNotStringAnyTupleArray(t)) {
    ;; t
    // ^?
  } else {
    ;; t // doesn't work
    // ^?
  }
  if (isStringAnyTupleArray(t)) {
    ;; t
    // ^?
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.