Cannot assign property to same type with generic key
See original GitHub issueTypeScript Version: 3.6.0-dev.20190803
Search Terms: assigning keyof generic key
Code
type A = { a: number }
type B = { b: number }
interface Foo {
a: A
b: B
}
declare let target: Foo
declare let source: Foo
declare let key: keyof Foo
target[key] = source[key]
Expected behavior:
I expect it to allow the assignment. Since typeof target
and typeof source
are the same, I expect typeof target[key]
to always be the same as typeof source[key]
.
Actual behavior:
error TS2322: Type ‘A | B’ is not assignable to type ‘A & B’.
Related Issues: #31665 (but it was closed and the comments seem to indicate that this should work 🤔) ping @RyanCavanaugh
Issue Analytics
- State:
- Created 4 years ago
- Reactions:11
- Comments:11 (2 by maintainers)
Top Results From Across the Web
TypeScript: Cannot assign object to a new property of an ...
I'm trying to figure out Typescript's generics, and I'm missing something very basic about them. const testFunction = <T extends {[key: ...
Read more >How to fix “Cannot assign to property: 'self' is immutable”
How to fix “Cannot assign to property: 'self' is immutable” ... SwiftUI's views should be structs, which means they are immutable by default....
Read more >Documentation - Utility Types - TypeScript
Constructs an object type whose property keys are Keys and whose property values are Type . This utility can be used to map...
Read more >Records - C# reference - Microsoft Learn
You can create record types with immutable properties by using positional ... you can't change the value of value-type properties or the ...
Read more >Restrictions on Generics (The Java™ Tutorials > Learning the ...
Cannot Instantiate Generic Types with Primitive Types. Consider the following parameterized type: class Pair<K, V> { private K key; private V value; ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
#31445 is the canonical one for this problem.
That said, I think we should revisit since it seems to be coming up reasonably often. Special-casing
a[k] = b[k]
for identical identifiersk
would fix 95% of these and in fact it’s hard to imagine a sound assignment where thek
s differedApproved for the case where
where
x
is an “identical reference” (the same function used for CFA). When this happens, relate the assignment using the old “union target” rules about the left-hand side instead of the newer stricter “intersection target” put in place. This would be a special case incheckBinaryExpression
. Ping me for clarification if needed.