-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Description
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.