-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Type annotation for object with unknown properties but known property types? #7803
Comments
or
or
It is called |
I'm just sharing in case it is useful for others... The following doesn't work: interface Metadata {
key: string,
value: any
}
interface MetadataObj {
[key: string]: Metadata
}
// no explicitly typed!
var metadata = {
someReducer: { key: "test", value: 1 } ,
anotherReducer: { key: "test", value: 2 }
// ...
};
function doSomething(metadata: MetadataObj) {
// ...
}
doSomething(metadata); The following works: interface Metadata {
key: string,
value: any
}
interface MetadataObj {
[key: string]: Metadata
}
var metadata : MetadataObj = { // type annotation here is needed
someReducer: { key: "test", value: 1 } ,
anotherReducer: { key: "test", value: 2 }
// ...
};
function doSomething(metadata: MetadataObj) {
// ...
}
doSomething(metadata); |
Here's a simpler test case: type Test = { [key: string]: { prop: number } };
let a: Test = { a: { prop: 1 } }; // <-- No error
let b = { a: { prop: 1 } };
let c: Test = b; // <-- Error in 1.8.9 This seems to be a bug that may have already been fixed. It errors in |
I believe it was fixed by #7029 (Implicit index signatures). It should probably be included on the next release. |
@malibuzios thanks for he details 😄 |
Just one question: Why do we have to name those variables? It is totally useless (if I'm wrong please enlighten me) |
I have encounter a few times in multiple applications an scenario in which I don't know the properties of an object but I do know that all its properties are of a certain type.
For example:
In this scenario:
metadata
Metadata
is the type of all the properties ofmetadata
Now let's imagine that a function take the metadata object as argument:
I used
any
as the type of the argument metadata but It would be great if I could let developers know that all the properties of this object must be of typeMetadata
.is there any way to create such type annotation?
The text was updated successfully, but these errors were encountered: