0

I have the following interfaces;

interface ComponentInterface {
    pollution: number,
    funds: number
}

interface ConfigInterface {
    pollution?: number,
    funds?: number
}

And then I have a function that creates objects based on the interfaces;

function create(oConfig: ConfigInterface = {}): ComponentInterface {
    // Merge the config with component defaults
    const oComponent: ComponentInterface = Object.assign({
        pollution: 0
    }, oConfig);

    // ...
}

And I'm calling the function without any arguments like;

create();

I don't understand why my compiler isn't throwing an error here. AFAIK I'm assigning { pollution: 0 } to a variable that's expecting a ComponentInterface.

1 Answer 1

1

The compiler is working well.
It does complain saying:

Type '{ pollution: number; } & ConfigInterface' is not assignable to type 'ComponentInterface'.
Property 'funds' is optional in type '{ pollution: number; } & ConfigInterface' but required in type 'ComponentInterface'.

Which is what you'd expect considering the signature of the function:

interface ObjectConstructor {
    assign<T, U>(target: T, source: U): T & U;
    ...
}

Where T is { pollution: number; } and U is ConfigInterface.

Also, You can also use Partial instead of redefining all props:

type ConfigInterface = Partial<ComponentInterface>;
Sign up to request clarification or add additional context in comments.

2 Comments

I had the same.
I looks at though it's just my compiler that isn't flagging it then! (atom-typescript 11.0.3)

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.