gpt4 book ai didi

typescript - 键入一个 "type predicate"没有任何

转载 作者:行者123 更新时间:2023-12-05 07:01:37 25 4
gpt4 key购买 nike

我在尝试正确键入我的函数之一时遇到问题。在下面的代码中,x 的类型是 any,我想输入比这更好的类型。

interface Pet {
name: string;
}

const checkType = (x: any): x is Pet => {
return 'name' in x && typeof x.name === 'string';
}

我发现 unknownobject 最合适,但两者都给我一个错误

interface Pet {
name: string;
}

const checkType = (x: unknown): x is Pet => {
return 'name' in x && typeof x.name === 'string';
}

Object is of type 'unknown'

interface Pet {
name: string;
}

const checkType = (x: object): x is Pet => {
return 'name' in x && typeof x.name === 'string';
}

Property 'name' does not exist on type 'object'


所以我的问题是,如何在不转换为 any 的情况下正确键入 x



以下可能是一个解决方案,但我发现它太多且具体了:

playground

interface Pet {
name: string;
}

const checkType = (x: object): x is Pet => {
return 'name' in x && typeof (x as {
name: unknown,
}).name === 'string';
}

更多信息:

任何可能导致问题的示例:

enter image description here

最佳答案

我建议通过以下两种方式之一解决此问题:

  1. 定义可能的输入类型的联合
  2. 定义键/值类型

第一个是 Typescript 手册中的示例所采用的方法(我假设您从中获得了“Pet”:

function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}

但是,如果您在通用库上工作,这会失败,因为您不知道您的消费者会为您提供什么,并且扩展该联盟并不是进行重大更改的好理由。然后你可以采取策略 #2:

interface IPojo {
[key: string]: any,
}

const checkType = (x: IPojo): x is Pet => {
return 'name' in x && typeof (x as {
name: unknown,
}).name === 'string';
};

function foo(p: Pet) {
console.log(p.name);
}

const bar: IPojo = {}
const baz = 'name';
bar[baz] = 'hi';

foo(bar); // TypeError, compiler can't verify bar.name
if (checkType(bar)) {
foo(bar); // No TypeError, type narrowed correctly by your guard
}

Playground

关于typescript - 键入一个 "type predicate"没有任何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63796285/

25 4 0