What is the difference between unknown
and any
types?
#1846
-
I didn't find the answer to this question on the wiki. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Assuming it is intended to mirror TypeScript:
---@param x any
local function double(x)
return x * 2
-- this is fine for a number, but what if someone passed in a boolean?
-- you would receive a runtime error, but type checking won't warn you because x is
-- annotated as accepting any type
end I think the ---@type unknown
local x
-- We aren't sure what `x` is...
if type(x) == "string" then
print("Now I am positive that x is a string")
end Again, this is using my knowledge from TypeScript, and it appears that the LSP currently does not have the same functionality. For example, In the example for I think there is still a lot of work to do with type narrowing and type checking in order to get |
Beta Was this translation helpful? Give feedback.
-
Thank you, @carsakiller! The first thing that occurred to me is that Although in practice this is not true. This code has no errors: ---@param x any
local function a(x)
return x * 2
end
---@param x unknown
local function u(x)
return x * 2
end
print(a(u(1))) So I still don't understand in what situations I should use |
Beta Was this translation helpful? Give feedback.
Assuming it is intended to mirror TypeScript:
any
is a value that is permitted to be anything; number, boolean, table, function - anything. It is often considered bad practice to label something asany
because it is then allowed to be whatever, and type checking will pretty much just ignore it, not providing any warnings - because again, it is allowed to beany
.I think the
unknown
type is relatively new to the LSP, but in TypeScript it …