In TypeScript, is there a type for truthy?
I have this method: Object.keys(lck.lockholders).length; enqueue(k: any, obj?: any): void think with TS there is a way to check for empty strings '', by the way. and I want to convert it to:
enqueue(k: Truthy, obj?: any): void
except I don't know how to define the type for Truthy. I think with TS there is a way to check for empty strings '', by the way.
The reason I want this is because I don't want users to pass in null
, undefined
, ''
, etc, as the key to a hash.
I'm not sure why you need this but it's interesting. In all honesty the short answer is: TypeScript isn't geared for this and you'd probably be better off doing runtime checks and documenting your code so that developers are aware that the
k
param should be truthy. Still, if you're set on trying to force TypeScript to do something like this, read on:Note: for the below to work, turn on the
strictNullChecks
compiler option. It's kind of necessary, since being unable to distinguishTruthy
fromTruthy | null | undefined
would be a problem.You can almost define falsy, which is like
except
NaN
is also falsy, and TypeScript doesn't have a numeric literal forNaN
.Even if you have
Falsy
as above, there are no negated types in TypeScript, so there's no way to expressTruthy
as "everything butFalsy
".You could try to use use conditional types to exclude possibly-falsy parameters in
enqueue()
, but it is weird:Note how it won't allow anything which it thinks might be falsy, which is possibly what you are trying to achieve. Can't tell.
Update
I see you edited the question to clarify that the
k
parameter should really be astring
(or possibly asymbol
) and that the only value you need to exclude is the empty string""
. In that case you could simplify the above to:All of that is great, but unfortunately there's the problem that if you pass a general
string
toenqueue()
it will fail, and sometimes a developer might need to do that if the value they are using for thek
parameter isn't a string literal they have specified:To deal with this, you can try to create a nominal type which you can use to identify to the compiler that a value has been checked for emptiness, and then make a user-defined type guard to constrain a
string
to that type:Now the developer can do this:
Whew! That's a lot of hoop jumping. It's up to you if you think this is worth it. Okay, hope that helps. Good luck!