在 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/