typescript - 在 TypeScript 中,是否有理由更喜欢 const foo : Type = {. ..} 或 const foo = { ... } 作为类型?

标签 typescript

在 TypeScript 中,有两种方法可以声明常量应该符合接口(interface):

interface Foo { x: string; }
const HELLO: Foo = { x: 'hello' };

interface Foo { x: string; }
const HELLO = { x: 'hello' } as Foo;

这些似乎具有相同的效果:TypeScript 将 HELLO 视为具有 Foo 类型,并将未出现在 interface 中的任何成员分配给它Foo 导致错误。

有什么理由更喜欢一种形式而不是另一种形式吗?它们完全等同吗?

最佳答案

在您的示例中,分配结果是相同的。但是,在第一个示例中键入变量的功能与在第二个示例中对变量进行类型转换的功能不同。

这是一个扩展的例子:

interface Foo { x: string; }
interface Foo2 extends Foo { y: string; }

// typing the variables
const hello: Foo = { x: 'hello' }; // works
const hello2: Foo2 = { x: 'hello', y: 'hello' }; // works
const hello3: Foo2 = { x: 'hello' }; // does not work because property 'y' is missing

// typecasting the variables
const hello4 = hello as Foo2; // works
const hello5 = hello2 as Foo2; // works
const hello6 = { x: 'hello' } as Foo2; // works

// typing the variables  
const hello7: Foo = {}; // does not work because property 'x' is missing
const hello8: Foo2 = {}; // does not work because property 'y' is missing
// typecasting the variables 
const hello9 = <Foo>{}; // works
const hello10 = <Foo2>{}; //works

// typing must match exact form, where typecasting does not, as long as interface is honored
const hello11: Foo = { x: 'hello', y: 'hello' }; // fails because of extra property 'y'
const hello12 = { x: 'hello', y: 'hello' } as Foo; // works

如您所见,仅当分配的对象具有完全匹配的形式时,键入变量才有效。即使赋值对象无效,也可以对变量进行类型转换,因为它本质上意味着您是在告诉 typescript ,您将确保它在某个时候确实如此。例如,如果您使用无效对象进行初始化,然后使用一些逻辑集剩余的缺失属性。

类型转换可以通过使用 as 来完成关键字或在分配的变量前加上 <type> .

关于typescript - 在 TypeScript 中,是否有理由更喜欢 const foo : Type = {. ..} 或 const foo = { ... } 作为类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41964087/

相关文章:

reactjs - 使用 neovim-lsp 和 tsserver 导入检测错误

node.js - Mongoose "property x does not exist on type y"错误 - 仍然有效

typescript - OpenAI GPT-3 API 错误 : "TypeError: openai.completions is not a function"

enums - 如何在 typescript 中定义和使用枚举?

angular - Angular 7 中 html 页面中来自嵌入式 Typescript 的更好的错误消息

javascript - 将模板分配给 Vue 类组件

reactjs - 如何输入文件上传的输入引用

angular - 在迭代期间通过 Angular 2 中的映射键检查表达式后,表达式已更改

jquery - 在 Typescript 类中访问 jquery 验证变量

typescript - WebStorm 就地编译 TypeScript 文件而不是生成到目标文件夹中