Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

typescript - Why do type assertions not validate as strongly as type declarations?

Given the following interface:

interface Request 
{
    name: string;
    email: string;
}

I would have thought that the following lines of code were functionally identical at design time:

var request1: Request = {name: "John"};
var request2 = {name: "John"} as Request;

But they are not. The second line compiles, whereas the first complains that the email property is missing.

If Typescript believes that all non-optional properties of the type must be specified, why doesn't it complain about type assertion using the as Request on an object that's missing a property.

And is there a casting syntax that would enforce this stronger typing? (The <Request>(...) syntax doesn't do so either.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The purpose of a type assertion (either the as Request syntax of the <Request> syntax) is to tell typescript "i know better than you, so don't check my work here". For that reason, type checking is more or less turned off. It still does a very loose form of typechecking to rule out the more egregious cases, but that won't catch the case you have. (And if it does find something you can turn it completely off by doing as unknown as Request).

And is there a casting syntax that would enforce this stronger typing?

If you want a strict type, then you use the colon syntax that you had on your first line.

var request1: Request = {name: "John"};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...