@property option for runtime schema validation
- Dominant language
- TypeScript
- Stars
- 21.8k
- Forks
- 1.1k
- Avg merge
- 18h 25m
- Merged PRs (30d)
- 2
Description
### Should this be an RFC?
- [x] This is not a substantial change
### Which package is this a feature request for?
Lit Core (lit / lit-html / lit-element / reactive-element)
### Description
It would be useful to have a concise way to do runtime validation of property values before they are set.
Strawperson:
```ts
@property({
parse: (value: unknown) => {
// ... do some schema validation
return value
}
});
```
I find myself wanting runtime validation like this for properties that hold complex types (e.g. component models). IIRC there is prior art for validation with some built-in elements, which will ignore sets for values that are of the wrong type.
Validation should of course be optional, and the default behavior should be pass-through, as before.
Possible approaches I can think of:
A parse function that returns `value | undefined`:
```ts
type Parse = (value: unknown) => T | undefined;
// Usage:
// @property({ parse })
```
A parse function that throws:
```ts
type Parse = (value: unknown) => asserts value is T;
// Usage:
// @property({ parse })
```
Either parse approach integrates fairly easily with validation libraries like Zod, and allows for coercion. Alternatively, a predicate?
A validation function that returns a boolean:
```ts
type Validate = (value: unknown) => value is T;
// Usage:
// @property({ validate })
```
### Alternatives and Workarounds
You can manually write the accessors, but it requires some additional ceremony.
```ts
#count = 0;
@property()
set count(value: number) {
if (typeof value !== "number") {
throw new TypeError("count must be a number");
}
this.#count = value;
}
get count() {
return this.#count;
}
```
Contributor guide
Research direction
Start with the Lit Core @property option and review how manually written accessors currently provide validation. Compare the proposed parse, throwing parse, and predicate approaches, including coercion and pass-through behavior. Done requires a decided validation API and corresponding behavior for complex property values.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- frontend, web-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100