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
Index signature alternative #32652
Comments
Related to #15300 I've often wanted things like this too, but to my knowledge the problem is that the compiler doesn't enforce that only known properties exist on an object. Without exact types there's no way to prevent something like the following: function folderMatcher(segments: UrlSegment[]): UrlMatchResult {
const posParamsWithRaisins = {
baseFolder: segments[1],
currentFolder: segments[0],
raisins: true // not a UrlSegment
};
const posParams: IUrlParameters = posParamsWithRaisins; // not an error
return {
consumed: segments,
posParams // should this work, or error?
};
} The assignment of Of course, the error goes away when you do this: function folderMatcher(segments: UrlSegment[]): UrlMatchResult {
const posParams = {
baseFolder: segments[1],
currentFolder: segments[0]
};
return {
consumed: segments,
posParams
};
} Why doesn't that work for you? If it's that you need to ensure that const asIUrlParameters = <T extends IUrlParameters>(x: T) => x;
function folderMatcher(segments: UrlSegment[]): UrlMatchResult {
const posParams = asIUrlParameters({
baseFolder: segments[1],
currentFolder: segments[0]
});
return {
consumed: segments,
posParams
};
} |
The proposition is to have a new kind of Index signature, that will only enforce all indexes to be of a type.
The point here is no that there would not be any way around it, but to address this very common problem that confuses many peoples. Using this ( |
Search Terms
Suggestion
An alternative of Index signature would be beneficial when you want to enforce, that all properties of an object must follow given pattern, without the need of
[key: string | number]: T1
.My suggestion is to enable the use of
?
for index signatures to mark them as type guards only.Use Cases
Whenever there is a need for an object with unknown keys, but known value types this would come in handy. A lot of people trying to implement some sort of callback that requires the index signature fails.The enormous number of results if one googles
Index signature is missing in type
confirms thisI personally tend to confront this problem regularly when working with frameworks..
Examples
For this example, I will use Angular, but this is applicable to any typescript code.
When one would be to implement it with only specific
posParams
it would only check for the type of the object keys and values.Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: