如何在TypeScript中为多个类型创建类型检查器?

kiz8lqtg  于 2023-05-01  发布在  TypeScript
关注(0)|答案(1)|浏览(103)

我为TypeScript中的原语创建了一个类型检查器:

type PrimitiveType = 'undefined' | 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol';

export class TypeChecker {
  static isOneOf(value: unknown, ...types: (PrimitiveType|null)[]): value is PrimitiveType | null {
    const allowedTypes = new Set(types);
    return allowedTypes.has(typeof value) || allowedTypes.has(null) && value === null;
  }
}

它可以用于:

const x: string|number|null = TypeChecker.isOneOf(value, 'string', 'number') ? value : null;

这个很好用。但是,在这种情况下,它会失败,因为编译器认为它是一个匹配:

const x: string|null = TypeChecker.isOneOf(value, 'string', 'boolean') ? value : null;

我怎样才能更新函数,使它知道我请求的类型?
我现在用的是TS 5。0.2.

6vl6ewon

6vl6ewon1#

type TypeofMap = {
    "string": string
    "number": number
    "bigint": bigint
    "boolean": boolean
    "symbol": symbol
    "undefined": undefined
    "object": object
    "function": Function
    "null": null
}
//                                                            minLength: 1
function checkType<T extends keyof TypeofMap>(value: unknown, ...types: [T, ...T[]]): value is TypeofMap[T] {
    let valueType = value === null ? 'null' : typeof value;
    //      set is not more efficient
    //      as requires cuz types is T[] but needed is (keyof TypeofMap)[] or string[]
    return (types as string[]).includes(valueType)
}
console.log(checkType('asd', 'null')) // false
console.log(checkType('asd', 'null', 'string')) // true
console.log(checkType('asd', 'string')) // true

相关问题