gpt4 book ai didi

typescript - else 分支上接口(interface)字段的类型保护

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

interface Test<T> {
field: string | T;
}

function isString<T>(test: Test<T>): test is Test<string> {
return typeof test.field === "string";
}

function f<T>(test: Test<T>) {
if (isString(test)) {
const a = test.field; // the type of a is string
} else {
const b = test.field; // the type of b is string | T
}
}

在上面的代码中,在if分支上,a的类型是string,这是正确的。但是,在 else 分支上,b 的类型是 string | T.

即使我为 T 添加检查,我也会得到相同的结果:

function isT<T>(test: Test<T>): test is Test<T> {
return typeof test.field !== "string";
}

function f<T>(test: Test<T>) {
if (isString(test)) {
const a = test.field; // the type of a is string
} else if (isT(test)) {
const b = test.field; // the type of b is string | T
}
}

我该怎么做才能不显式地将 b 转换为 T,就像我不需要将 a 转换为 字符串?

最佳答案

问题是 user-defined type guard正在检查 Test<T> 的类型, 但你想要的是 field 的类型.

你的分支看起来像这样:

function f<T>(test: Test<T>) {
if (isString(test)) {
// We have a `Test<string>`
const a = test.field;
} else {
// We do not have a `Test<string>`
const b = test.field;
}
}

if分支,我们有一个Test<string> , 及其 field属性是 string | string 的联合(这只是一个 string )。类型看起来像这样:

interface Test<string> {
field: string | string;
}

else分支,我们有一个Test<SomeNonString> , 及其 field属性是 string | SomeNonString 的联合.它的类型如下所示:

interface Test<SomeNonString> {
field: string | SomeNonString;
}

在那else分支,我们需要消除歧义,因为field仍然是联合类型。只要Test<T>接口(interface)定义 field作为 string | T 的联合类型,我们将需要后续测试,无论何时 T不是 string .

这是一个例子:

function isFieldString<T>(field: string | T): field is string {
return typeof field === "string";
}

function f<T>(test: Test<T>) {
if (isString(test)) {
const s = test.field; // const s: string
} else if (isFieldString(test.field)) {
const s = test.field; // const s: string
} else {
const t = test.field; // const t: T
}
}

关于typescript - else 分支上接口(interface)字段的类型保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45908789/

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