0

In TypeScript you frequently have an external interface definition to a JS library where many, if not all of the fields are optional, usually because there are quite a few fields and you wouldn't want to force a user of the library to fill them all in. Most fields will have sensible defaults.

So when declaring the interface you mark the fields as optional with ?. But this severely limits type checking with object literals as now it won't catch property name typos. Because any object fulfills the interface, so does any object with an extra property that happens to be a typo of an actual property.

See Example:

interface SomeExternalLibraryConfiguration {
    prop1 ? : number;  //Defaults to 0;  
    prop2 ? : string;  //Defaults to null
    prop3 ? : boolean; //Defaults to true
}

//This works fine
var conf1 : SomeExternalLibraryConfiguration = { prop1 : 10, prop2 : 'hello', prop3: false};

//So does this
var conf2 : SomeExternalLibraryConfiguration = { prop1 : 10};

//So does this, compiler flags the wrong type
var conf3 : SomeExternalLibraryConfiguration = { prop1 : '10'};

//But what about this?  No love from the compiler - how to I get the compiler to recognize the typo?
var conf4 : SomeExternalLibraryConfiguration = { prap1 : 10};

//Oddly though this is only a problem with object literals, as here the compiler does what I want and flags prap1
var conf5 : SomeExternalLibraryConfiguration;
conf5.prap1 = 10;

Is there a way to tell the compiler "I want this object literal to fulfill this interface, and only this interface"?

1

1 Answer 1

1

I want this object literal to fulfill this interface, and only this interface

Not at the moment. Sound like a good feature request for https://github.com/microsoft/typescript/issues

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.