From cc1073517c1ef1447186f96ac8bf4fbe29d43165 Mon Sep 17 00:00:00 2001 From: Erica Marigold Date: Tue, 29 Oct 2024 18:07:17 +0530 Subject: [PATCH] Fix string length type function example in Luau blog post --- src/content/posts/luau-for-js-devs/index.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/content/posts/luau-for-js-devs/index.md b/src/content/posts/luau-for-js-devs/index.md index 70cd8e5..239a92b 100644 --- a/src/content/posts/luau-for-js-devs/index.md +++ b/src/content/posts/luau-for-js-devs/index.md @@ -60,21 +60,22 @@ localeFn("en-gb") // TypeError: Argument of type 'string' is not assignable to p ``` ```luau -type function IsStringOfLength(s: string, length: number) - if #s ~= length then +type function IsStringOfLength(s, length) + local lenNum = tonumber(len:value()) + assert(s:is("singleton") and typeof(s:value()) == "string", "s must be of type string") + assert(len:is("singleton") and lenNum ~= nil, "len must be of type number") + + if #s:value() ~= lenNum then return error("Expected country code to be 2 characters") end return s end -type LocaleCountryCode = IsStringOfLength -local function localeFn(code: LocaleCountryCode) - -- Do something -end +type LocaleCountryCode = IsStringOfLength -localeFn("gb") -- This is fine -localeFn("en-gb") -- TypeError: Expected country code to be 2 characters +local gb: LocaleCountryCode<"gb"> -- This is fine +local enGb: LocaleCountryCode<"en-gb"> -- TypeError: Expected country code to be 2 characters ``` The Luau implementation in the form of a type function is not only more readable and intuitive, it also allows for entirely customizable error diagnostics. Such a pattern is common in Luau's type system design, which emphasizes on types not overshadowing code or requiring a pHD to write due to complexity.