Skip to content

Inference issue in literal objects #23109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
pauliusrum opened this issue Apr 3, 2018 · 1 comment
Closed

Inference issue in literal objects #23109

pauliusrum opened this issue Apr 3, 2018 · 1 comment

Comments

@pauliusrum
Copy link

I have noticed a problem with type inference of literal objects. Given example where alignment property should be of type "left" but it is string instead and it is not accepted by the given printText function when it is passed as a variable params but work when it is specified directly at the function invocation. Does this work as intended or is it a bug?

Tested with Typescript 2.8.

type Alignment = "left" | "right" | "center"

const params = {
    alignment: "left"
}

function printText(text: string, options: { alignment: Alignment }) {
    console.log(text)
}

printText("Test", params) // Compile error
printText("Test", { ...params }) // Compile error
printText("Test", {alignment: "left"}) // Correct
@MartinJohns
Copy link
Contributor

MartinJohns commented Apr 3, 2018

Working as intended: #20271

A sensible rule (perhaps enforced with tslint?) is that when you assign a created object literal to a variable it should always be typed. Only then the "object literal may only specify known properties" check will work too, informing you about obsolete properties when you removed it from the type but not in the code.

@microsoft microsoft locked and limited conversation to collaborators Jul 25, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants