在 TS 中解构一个对象

Destructuring an object in TS

我有这个 TS 代码,我想让那个部分也被输入:

    const { data: { person, car, another } }: any = useContext(MyContext);

这里的问题是 ES lint 说: warning Unexpected any. Specify a different type @typescript-eslint/no-explicit-any

我为 person、car 和 another 创建了 3 个接口,我想在 useContext 之后重用它们。 我的objective只是分享人、车、其他

有什么线索吗?

类型注解不能放在解构操作中,: 字符已经在那里用作将被解构的 属性 分配给新名称的方法。

const { person: p2 } = { person: "Name" }
p2 === "Name" // true

您可以将 any 替换为您期望 useContext 的类型。

const { data: { person, car, another } }: { data: { person: Person, car: Car, another: Another } }
  = useContext(MyContext);

但理想情况下,useContext 的 return 的类型应该从传递给它的参数中推断出来,当您创建上下文时,您应该有这样一行:

type ContextType = {data: {person: Person, car: Car, another: Another}}
const MyContext = createContext<ContextType>({/* default value */})

当您随后使用 useContext 时,returned 的值将已经具有 ContextType 并且您的解构将被键入而无需任何类型注释。