gpt4 book ai didi

typescript - 通过 "is"运算符和条件类型缩小通用类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:09:52 31 4
gpt4 key购买 nike

我想使用 is 运算符将泛型类型缩小为“原始类型的联合”或简单的 object 类型。无论哪种方式都适用于我的用例。

以下代码段的正确解决方法是什么? ( playground )

class Foo<T = any> {
constructor(value: (() => T) | (T extends Function ? never : T)) {}
}

// Function values must be returned by a getter:
new Foo(() => () => {}) // OK: Inferred as "Foo<() => void>(value: () => () => void)"

// All other values can be optionally wrapped with a getter, or passed as-is:
new Foo(() => 1) // OK: Inferred as "Foo<1>(value: 1 | (() => 1))"
new Foo(1) // OK: Inferred as "Foo<1>(value: 1 | (() => 1))"

// Try narrowing to a primitive type:
function testPrimitive<T>(value: T) {
if (isPrimitive(value)) {
return new Foo(value) // ERROR: "Type 'T & string' is not assignable to type 'T & symbol extends Function ? never : T & symbol'."
}
}

// Try narrowing to an object type:
function testObject<T>(value: T) {
if (isObject(value)) {
return new Foo(value) // ERROR: "Type 'T & object' is not assignable to type 'T & object extends Function ? never : T & object'."
}
}

type Primitive = string | number | boolean | symbol | null | undefined

const isPrimitive = (value: any): value is Primitive =>
!value || typeof value !== 'object'

const isObject = (value: any): value is object =>
value && typeof value === 'object'

最佳答案

让我们定义基础:

type Primitive = boolean | number | string | symbol | null | undefined;


class Foo<T> {
constructor(value: T | (T extends Function ? never : T)) {}
}

new Foo(() => 1)
new Foo(1)

如果我们这样定义 isPrimitiveisObject:

declare function isPrimitive(argument: unknown): argument is Primitive;
declare function isObject<T extends object>(argument: T | Primitive): argument is T;

我们在调用点得到正确的类型推断:

function testPrimitive(argument: unknown) {
if (isPrimitive(argument)) {
return new Foo(argument);
}
}

function testObject<T extends object>(argument: T | Primitive) {
if (isObject(argument)) {
return new Foo(argument);
}
}

Playground

关于typescript - 通过 "is"运算符和条件类型缩小通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54192291/

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