Skip to content

Introduce "extends const" syntax #32666

@pleerock

Description

@pleerock

Imagine we have some interface:

export type User = {
    id: number
    name: string
}

Working as expected:

And we have a function register1 that accepts Partial of this type:

function register1(userProperties: Partial<User>) {
}

register1({
    id: 1,
    name: "Anders",
})

And I want to prevent incident properties passing to that function:

register1({
    id: 1,
    name2: "Anders", // gives me error, great!
})

Not working as expected:

Now imagine I have a register2 function that does the same, and a bit more:

function register2<T extends Partial<User>>(properties: T) {
    // I want to pass T down the road to another function, 
    // and that function returns type-safe result based on actually passed properties
    // let's imagine that function changes given property values to boolean
    return someAnotherFunctionCall<T>(properties)
}

register2({
    id: 1,
}) // returns { id: boolean }

register2({
    id: 1,
    name2: "Anders"
}) // returns { id: boolean } as expected 

Everything works as I need besides one thing - I would like compiler to throw error on name2 property - "missing property name2 on Partial" (to prevent mistakes or refactoring consequences). I understand why I have this error - because T extends Partial<User> means T is extended version of Partial and supposed to have any additional properties. But how can I achieve what I need? Looks like I need a "final" version of Partial. Maybe something like T extends const Partial<User> syntax should be suggested?

It can be a duplicate, I didn't know how to describe problem properly. If it's a new feature please help me to update the issue title. Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions