mirror of
https://github.com/CompeyDev/blog.devcomp.xyz.git
synced 2024-12-12 04:40:41 +00:00
Fix string length type function example in Luau blog post
This commit is contained in:
parent
822656c330
commit
cc1073517c
1 changed files with 9 additions and 8 deletions
|
@ -60,21 +60,22 @@ localeFn("en-gb") // TypeError: Argument of type 'string' is not assignable to p
|
||||||
```
|
```
|
||||||
|
|
||||||
```luau
|
```luau
|
||||||
type function IsStringOfLength(s: string, length: number)
|
type function IsStringOfLength(s, length)
|
||||||
if #s ~= length then
|
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")
|
return error("Expected country code to be 2 characters")
|
||||||
end
|
end
|
||||||
|
|
||||||
return s
|
return s
|
||||||
end
|
end
|
||||||
|
|
||||||
type LocaleCountryCode<T> = IsStringOfLength<T, 2>
|
type LocaleCountryCode<T> = IsStringOfLength<T, "2">
|
||||||
local function localeFn<T>(code: LocaleCountryCode<T>)
|
|
||||||
-- Do something
|
|
||||||
end
|
|
||||||
|
|
||||||
localeFn("gb") -- This is fine
|
local gb: LocaleCountryCode<"gb"> -- This is fine
|
||||||
localeFn("en-gb") -- TypeError: Expected country code to be 2 characters
|
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.
|
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.
|
||||||
|
|
Loading…
Reference in a new issue