[英]What's the difference between using `: Interface` and `as Interface` in Typescript?
I'm not sure what these are called so I'm having a bit of trouble searching for an answer.我不确定这些叫什么,所以我在寻找答案时遇到了一些麻烦。 Let's say I have the following interface defined:
假设我定义了以下接口:
interface Person {
name: string;
age: number;
}
What's the difference between the following?以下有什么区别?
const foo: Person = getPerson(data);
and和
const foo = getPerson(data) as Person;
Seems like both tell TS that foo
is a Person
.似乎两者都告诉 TS
foo
是Person
。 Is there fundamentally any difference or is it just a matter of using whatever floats my boat?从根本上来说有什么区别,还是只是使用我船上的任何东西?
With和
const foo: Person = getPerson(data);
you tell the compiler: I assume that getPerson
returns something that implements the Person
interface, please check that and scold me if it doesn't.你告诉编译器:我假设
getPerson
返回了实现Person
接口的东西,请检查一下,如果没有,就骂我。
const foo = getPerson(data) as Person;
is an assertion, with which you assure the compiler that getPerson
returns a Person
, even if they mean otherwise.是一个断言,你可以通过它向编译器保证
getPerson
返回一个Person
,即使它们的意思不是这样。 Basically, it's a way to shut up the type checker, and, mostly, not a good idea.基本上,这是一种关闭类型检查器的方法,而且大多数情况下,这不是一个好主意。
const foo: Person = getPerson(data);
Is a type annotation, and means you're saying "I want foo
to be of type Person
".是一个类型注释,意味着你说“我希望
foo
是Person
类型”。 However, if getPerson(data)
returns something other than a Person
, TypeScript will say "No no no, that's not allowed. You want Person
but getPerson(data)
does not return that, bad!"但是,如果
getPerson(data)
返回的不是Person
, TypeScript 会说“不,不,这是不允许的。你想要Person
但getPerson(data)
不返回那个,糟糕!”
const foo = getPerson(data) as Person;
as Person
is a type assertion, if you wrote this without the as Person
, TypeScript would infer foo
to be the type of whatever getPerson(data)
returns. as Person
是一个类型断言,如果你在没有as Person
的情况下编写了这个,TypeScript 会推断foo
是getPerson(data)
返回的任何类型。 However, by adding the as Person
you are telling TypeScript, explicitly, "Whatever this function returns, even if it's not actually a Person
, I am forcing you to type it as a Person
".但是,通过添加
as Person
你是在告诉 TypeScript,明确地说,“无论这个 function 返回什么,即使它实际上不是一个Person
,我强迫你把它输入一个Person
”。
Hope that answers it somewhat.希望能回答它一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.