Skip to content

Spreading constrained generic parameters allows for invalid/unsafe return types #61754

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

Open
WadePeterson opened this issue May 22, 2025 · 1 comment

Comments

@WadePeterson
Copy link

πŸ”Ž Search Terms

spread generic
spread generic unsafe
spread constrained generic invalid

πŸ•— Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about "generics" and "spread"

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/JYOwLgpgTgZghgYwgAgILIN4Chm+XALmQGcwpQBzHPAIyJAFcBbG6LAXyyxgZATGAB7EMkikAjAAoAJnDCE0ASiLpseZFAhgGUEWvV4AdMdnyANNQPI6yAOQxgANwi3kAejfIEgqJv4AbAE9kaCgfYiIAFUCABxRbUnIQCldgYmQQQTB8YmJgChA4Gn8UMEFRWPjGFmhbQ0tkTk5uXn4hETEwACYAHkiQgA9IEGl01AA+GTkFSOU0TAbNbV0Fq1xjQ1M4CzXrInsnF3dPaUEIdMzs0J8zawZs4gALQQZ-aUMNLR0QdNBHOH8wGkyEENAAVhB+A0mlggA

πŸ’» Code

interface A {
    a: string
    b: number
}

function test1(data: A): A {
    return {
        ...data,
        b: 'five' // correctly errors: Type 'string' is not assignable to type 'number'.
    }
}

function test2<T extends A>(data: T): A {
    return {
        ...data,
        b: 'five' // does not error, but should. returns invalid object
    }
}

πŸ™ Actual behavior

test2 function compiles without error, but when called at runtime, will always return an invalid object, with property b of type string instead of number

πŸ™‚ Expected behavior

test2 function has a compiler error preventing spreading of the b property with an invalid value.

Additional information about the issue

I found a similar issue, #60623

However, this issue has a more complex case, with an example function returning a generic. In my example, test2 declares a static return type, and unambiguously returns an invalid value that does not satisfy that type.

@jcalz
Copy link
Contributor

jcalz commented May 22, 2025

This is still #10727; TS doesn't have a native spread type operator. The closest thing it has is intersection, which is simple and often good enough... except when you overwrite properties with incompatible types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants