简体   繁体   中英

Typescript: adding only an optional property removes type checking

I'm using typescript 1.4.1 and have the following code:

var hello: {message: string};
hello = {world: 't'};

As intended, the typescript compiler outputs an error:

Type '{ world: string; }' is not assignable to type '{ message: string; }'. Property 'message' is missing in type '{ world: string; }'. (var) hello: { message: string; }

But if the type contains only an optional property such as in:

var hello: {message?: string};
hello = {world: 't'};

Then the compiler is perfectly happy, but I would like the error to be detected.

What am'I doing wrong? or is it a typescript bug?

Thanks for your help!

Then the compiler is perfectly happy, but I would the error to be detected. What am'I doing wrong? or is it a typescript bug?

No this is by design. extra information is okay as long as the required information (in this case nothing) is present.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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