From 29656fd7d6bb2091baf100348838e77fa3e8e991 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 30 Oct 2022 21:57:17 -0500 Subject: [PATCH] Add Create A Non-Empty Array Type as a TypeScript TIL --- README.md | 3 +- typescript/create-a-non-empty-array-type.md | 35 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 typescript/create-a-non-empty-array-type.md diff --git a/README.md b/README.md index f5b16c9..8334347 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1261 TILs and counting..._ +_1262 TILs and counting..._ --- @@ -1168,6 +1168,7 @@ _1261 TILs and counting..._ - [Add Types To An Object Destructuring](typescript/add-types-to-an-object-destructuring.md) - [Compiler Checks For Unused Params And Variables](typescript/compiler-checks-for-unused-params-and-variables.md) +- [Create A Non-Empty Array Type](typescript/create-a-non-empty-array-type.md) - [Create A Union Type From An Array](typescript/create-a-union-type-from-an-array.md) - [Create Union Type From Constants](typescript/create-union-type-from-constants.md) - [Extract Object Type Keys Into A Union Type](typescript/extract-object-type-keys-into-a-union-type.md) diff --git a/typescript/create-a-non-empty-array-type.md b/typescript/create-a-non-empty-array-type.md new file mode 100644 index 0000000..6ba58bc --- /dev/null +++ b/typescript/create-a-non-empty-array-type.md @@ -0,0 +1,35 @@ +# Create A Non-Empty Array Type + +An array type (e.g. `Array`) by default will allow an empty array. We +can define a custom array type that does static type checking to ensure arrays +aren't declared as empty. + +To do this, we specify the array type has at least one item in addition to the +_spread_ of the rest of the array. + +```typescript +type NonEmptyArray = [T, ...T[]]; +``` + +If we declare a `NonEmptyArray` with no items: + +```typescript +const statuses: NonEmptyArray = []; +``` + +We'll get the following type error: + +``` +Type '[]' is not assignable to type 'NonEmptyArray'. + Source has 0 element(s) but target requires 1. +``` + +Whereas as soon as we add at least one item, the type error goes away. + +```typescript +const statuses: NonEmptyArray = ['active']; +``` + +Here is a [TS Playground example of this type](https://www.typescriptlang.org/play?#code/C4TwDgpgBAcg9gOwKIFsygIICcsEMQA8AKgHxQC8UA2kQDRQB0TRVAuqwNwBQXAxogGdgUCGlABlYLmABXARAEAuWIlToQ2PISFYAlggDmZSm259BwodLkLl8ZGI058BHfqMVqAcly9gugDcIL04gA). + +[source](https://twitter.com/he_zhenghao/status/1583557892480778240)