Skip to content

Incorrect type inference when using spread operator with index signature and adding another prop #49920

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
danmana opened this issue Jul 15, 2022 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@danmana
Copy link

danmana commented Jul 15, 2022

Bug Report

πŸ”Ž Search Terms

typescript spread wrong type inference

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried (ex: 3.3.3-4.7.4)

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface A {
    title: string
    [year: number]: number
}
let a: A = {title: 'A', 2020: 123};

let b = { ...a}
let c = { ...a, label: 'revenue'}

πŸ™ Actual behavior

// d.ts inference
declare let b: {
    [x: number]: number;
    title: string;
};
declare let c: {
    label: string;
    title: string;
};

πŸ™‚ Expected behavior

// d.ts inference
declare let b: {
    [x: number]: number;
    title: string;
};
declare let c: {
    [x: number]: number; // <--- this is missing
    label: string;
    title: string;
};

It seems that when I add an extra property to the spread object, it loses the index signature properties from the spread source.
But, if I do not add any extra property it does infer correctly the type...

@MartinJohns
Copy link
Contributor

Duplicate of #27273. Used search terms: spread index in:title

@danmana
Copy link
Author

danmana commented Jul 15, 2022

Yes, I think you are right and it's a duplicate ... sorry I missed that

For context, this situation is slightly different as there is no overlap in the keys [x: number]: number and label: string, unlike the linked issue which uses Record<string, string> and a: '' where there is no obvious resolution.
I'm not sure if this is a relevant enough distinction to keep this issue open.

For reference, as mentioned in the comments there, Object.assign does produce an expected result

let d = Object.assign({}, a, {label: 'revenue'})

// infered d.ts
declare let d: A & {
    label: string;
};

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jul 29, 2022
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants