简体   繁体   English

将类型断言与解构赋值一起使用的最佳方法是什么?

[英]What's the best way to use a type assertion with destructuring assignment?

I have some code using destructuring assignment as follows:我有一些使用解构赋值的代码,如下所示:

const { values: project, setValues, submitForm } = useFormikContext();

Per the TypeScript type assertion documentation I'd like to use the as keyword to tell the TS compiler that project will always be the type Project .根据TypeScript 类型断言文档,我想使用as关键字告诉 TS 编译器project将始终是类型Project

What's the correct syntax for this?什么是正确的语法? I've tried:我试过了:

const { values: (project as Project), setValues, submitForm } = useFormikContext();

but that's invalid.但这是无效的。

By looking at the implementation the definition uses TypeScript Generics通过查看实现,定义使用TypeScript Generics

export function useFormikContext<Values>() {
  const formik = React.useContext<FormikContextType<Values>>(FormikContext);

  return formik;
}

it creates a react context and if you call the hook as:它会创建一个反应上下文,如果您将钩子称为:

useFormikContext<Project>()

probably not only the values will be of type Project , but also setValues would accept only object of type Project (unfortunately haven't used the library)可能不仅值的类型是Project ,而且setValues也只接受 object 类型的Project (不幸的是没有使用该库)

You can use the following syntax to approach this:您可以使用以下语法来解决此问题:

const { values: project, setValues, submitForm }: { values: Project; setValues: SomeType1, submitForm: SomeType2} = useFormikContext();

You can create another variable, as well:您也可以创建另一个变量:

const { values: project, setValues, submitForm } = useFormikContext();
const a: Project = project;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM