Skip to content

Allow separate read and write types for index signatures to support Proxies #45887

@muzam1l

Description

@muzam1l

Suggestion

Es6 Proxy is one of the most powerful and sweet features of JavaScript, it can particularly give JavaScript programmers ability to have different setter/getter behaviors on index properties. But TypeScript just ruins the experience, despite similar practices found largely in DOM Api's.

If Typescript can't infer Proxy types, at least provide more powerful index signatures typing, allowing getter setter to have different types.

📃 Motivating Example

/*
interface TargetObj<S extends object> {
  [K in keyof S]: Wrapper<S[K]> // wrapper object just stores that value, with type from generic
}
targetObj: TargetObj<skipping S signature> = {
  key1:  new Wrapper(1)
  key2: new Wrapper('string')
}
obj = new Proxy(targetObj , {
  get(target, prop) return  target[prop].value
  set(target, prop, value) {
    obj[prop] = new Wrapper(value)
  }
})
obj.key1 // -> Wrapper { value: 1 }
obj.key1 = 5
obj.key2 = 'another string'
obj.key1 // -> Wrapper { value: 5 }
obj.key2 // -> Wrapper { value: 'another string' }

Now TypeScript wont allow this and I can't even set index signatures with varying signatures of getter and setter.

⭐ Suggestion

Infer Proxy types or at least support different getter/setter for index signatures like this.

interface TargetObj<S extends object> {
  get [K in keyof S]: Wrapper<S[K]> // wrapper object just stores that value
  set [K in keyof S]: S[K]
}

🔍 Search Terms

List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily and help provide feedback.

Proxy type inferring, different getter/setter signatures on index properties, etc

✅ Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

💻 Use Cases

Proxy support.

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