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
Objects with unknown property names #43
Comments
Hi, thanks for bring this up! I still didn't have the time to look into it, I think the best solution will be to implement some const PointSchema = Schema({ x: number, y: number });
const PointMapSchema = object.test((obj) => Object.values(obj).every(PointSchema)); |
Thanks for responding! It's not urgent but good to know about the example you provided! Having some sort of |
Proposed interface: import { Record, string, number } from 'computed-types';
const PointMap = Record(string, { x: number, y: number }); |
In a |
The key validator will be any value that can as as an object property (number, string or symbol). You will be able to provide any validator such as: |
Hi, here is a generic version that I created today, which seems to work well and will also create the correct type Validator<T> = (value: any) => T; // I can't find if/where this type is exported from computed_types?
export const Record = <KeyType extends string | number | symbol, ValueType>(keySchema: Validator<KeyType>, valueSchema: Validator<ValueType>) => {
return (object
.test((obj) => Object.values(obj).every(valueSchema) && Object.keys(obj).every(keySchema))
.transform(obj => obj as Record<KeyType, ValueType>)
);
}
Yep, that is working. |
Are there plans to release this? |
I don't have the time right now. You're welcome to create a PR. |
Released in |
Awesome, thank you! |
Very often I'll encounter situations where I need to type an object that has unknown property names (e.g. an id or a key) but the shape of its value is known.
e.g.
I can't really figure out how to accomplish that with computed-types.
The text was updated successfully, but these errors were encountered: