From e8304cdeb8012cf186d5a19ac2a7b50cee59d7a4 Mon Sep 17 00:00:00 2001 From: Rebecca Stevens Date: Thu, 16 Jul 2020 14:31:02 +1200 Subject: [PATCH] docs: add info to readme about optional properties --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index 4b0de2d..342852c 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,30 @@ const isCompany = isOfShape({ isCompany({name: 'Untitled', users: [{name: 'John', age: 21}]) // => true ``` +#### Optional Properties + +If a property can optionally be defined, wrap the type guard for it in `optional`. + +```ts +type User = { name: string; perferredName?: string }; +const isUser = isOfShape({ name: isString, perferredName: optional(isString) }) + +isUser({name: 'John'}) // => true +isUser({name: 'John', perferredName: 'Johnny'}) // => true +isUser({name: 'John', perferredName: undefined}) // => true +``` + +Note: this is different from using `isOneOf` with `isUndefined`. + +```ts +type User = { name: string; perferredName: string | undefined }; +const isUser = isOfShape({ name: isString, perferredName: isOneOf(isString, isUndefined) }) + +isUser({name: 'John'}) // => false - `perferredName` must be defined. +isUser({name: 'John', perferredName: 'Johnny'}) // => true +isUser({name: 'John', perferredName: undefined}) // => true +``` + ### `isOfExactShape` The same as `isOfShape`, except that it excludes objects that have extra keys