Search code examples
typescripttypescript2.0tsc

TypeScript type representing everything but undefined


I have a function like so:

export const logToStdout = function(v: NotUndefined){

  console.log(JSON.stringify({
        marker: '@json-stdio',
        value: v
   });
}

what I would like to have is a definition for NotUndefined that is everything but undefined.

You can see the problem when running:

console.log(JSON.stringify({value: ''}));
console.log(JSON.stringify({value: undefined}));

what would be kind of nifty would be:

export type NotUndefined = !undefined; 

what is the right way to do this?

I see this related issue in on Github for TS: https://github.com/Microsoft/TypeScript/issues/7648

I tried this methodology, but there is no error:

enter image description here

Before you complain, here is the code/gist: https://gist.github.com/ORESoftware/e138f1840302c79b4ffc5f961337c44b


Solution

  • You need to enable strict null checks, otherwise null and undefined are implicitly added as valid values for every type.

    References: