Skip to content
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

Looking for an official type side (not user side) solution to the problem of no inference on string literals nested in object literals #42257

Closed
shamilovtim opened this issue Jan 8, 2021 · 6 comments
Labels
Duplicate An existing issue was already created

Comments

@shamilovtim
Copy link

shamilovtim commented Jan 8, 2021

Bug Report

🔎 Search Terms

prevent type widening in nested string literal in object literal inference

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type widening on string literals

This is a pre-existing issue and deals with the way that the compiler does type inference on object literals

⏯ Playground Link

Playground link with relevant code

💻 Code

type User = {
    id: number;
    name: string;
    type: "member" | "editor" | "admin";
}

const LoginScreen = () => {

    const bob = {
        id: 1,
        name: "Bob",
        type: "member";
    }

    const getUser = (user: User) => {
        // do whatever
        return user.id;
    }

    // Argument of type '{ id: number; name: string; type: string; }' is not assignable to parameter of type 'User'.
    //   Types of property 'type' are incompatible.
    //     Type 'string' is not assignable to type '"member" | "editor" | "admin"'.(2345)
    getUser(bob);
}

🙁 Actual behavior

The string literal in bob was widened from "member" to string.

🙂 Expected behavior

Since the compiler knows that bob is being passed into getUser and never mutated it should know that bob is is unambiguously of type User and that the user of my type definitions doesn't need an explicit assertion or type on bob.

I don't want my users to have to assert bob as const or have to import User to explicitly define const bob: User ={...} I want my users to be able to use dynamically typed variables AND have type inference on the string literals in my nested objects in situations when the compiler should know the intention behind the variable. Please consider:

Please provide a type side solution to this issue rather than asking our users to work around it. Does one exist? If so, could you please define it in the TypeScript FAQ, as this problem is common, and googling for it is difficult due to misleading solutions that ask the user to assert the variable.

@shamilovtim
Copy link
Author

Further thoughts. If the reason no modifier has been provided thus far on the type side to fix this is because it's unsafe then let us have the option to be unsafe. We already have the options to set strict mode (or not) and some of us don't need that level of type safety. Let us back out and let our users use the language dynamically where they need to. Please consider providing a modifier on the type side that would increase the inference on string literals in this particular situation rather than asking our users to work around it with modifiers on their side.

@RyanCavanaugh
Copy link
Member

Since the compiler knows that bob is being passed into getUser and never mutated it

It doesn't, though, and it can't. You could induce an unsoundness here by a later legal unaliased mutation to bob. as const is the thing that prevents that mutation and causes the code to typecheck - those things are linked for a reason. If you're OK with sometimes getting out-of-type values, string is the right type to give this field.

type User = {
    id: number;
    name: string;
    type: "member" | "editor" | "admin";
}

const LoginScreen = () => {

    const bob = {
        id: 1,
        name: "Bob",
        type: "member"
    }

    const getUser = (user: User) => {
        if (user.name !== "member" && user.name !== "editor" && user.name !== "admin") {
            throw new Error("Failed!");
        }
        // do whatever
        return user.id;
    }

    // Argument of type '{ id: number; name: string; type: string; }' is not assignable to parameter of type 'User'.
    //   Types of property 'type' are incompatible.
    //     Type 'string' is not assignable to type '"member" | "editor" | "admin"'.(2345)
    getUser(bob);

    return { bob, getUser } ;
}

// Later, in a different module that TypeScript can't see when analyzing the prior code:
const p = LoginScreen();
p.bob.name = "quack";
// Throws
p.getUser(p.bob);

@shamilovtim
Copy link
Author

Since the compiler knows that bob is being passed into getUser and never mutated it

It doesn't, though, and it can't. You could induce an unsoundness here by a later legal unaliased mutation to bob. as const is the thing that prevents that mutation and causes the code to typecheck - those things are linked for a reason. If you're OK with sometimes getting out-of-type values, string is the right type to give this field.

type User = {
    id: number;
    name: string;
    type: "member" | "editor" | "admin";
}

const LoginScreen = () => {

    const bob = {
        id: 1,
        name: "Bob",
        type: "member"
    }

    const getUser = (user: User) => {
        if (user.name !== "member" && user.name !== "editor" && user.name !== "admin") {
            throw new Error("Failed!");
        }
        // do whatever
        return user.id;
    }

    // Argument of type '{ id: number; name: string; type: string; }' is not assignable to parameter of type 'User'.
    //   Types of property 'type' are incompatible.
    //     Type 'string' is not assignable to type '"member" | "editor" | "admin"'.(2345)
    getUser(bob);

    return { bob, getUser } ;
}

// Later, in a different module that TypeScript can't see when analyzing the prior code:
const p = LoginScreen();
p.bob.name = "quack";
// Throws
p.getUser(p.bob);

Really appreciate the response Ryan. While using string as the type definition is there any kind of alternative where we can both have it defined as string but also present the enumerated values to the user in the type definition? Is it pretty much a JSDoc only side solution or are there any further alternatives I am unaware of?

@RyanCavanaugh
Copy link
Member

Not really. In the meantime you could write "x" | "y" | string and hope that we find a good solution for #29729 (previously discussed at #38951).

@shamilovtim
Copy link
Author

Gotcha, appreciate all of the useful feedback! Hopefully this thread is a little bit more searchable for the next dev who has this conundrum.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 8, 2021
@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

3 participants