TS Compiler API: How do I get type of 'unknown' from TypeScript's TypeChecker?

56 views Asked by At

TypeScript's TypeChecker API has functions like getAnyType and getUndefinedType, but there appears to be no getUnknownType. How do I get unknown as a Type to use for equality checks?

I've used typeToString to convert Type to unknown for equality checks in other cases, but for this case I need the Type version of unknown and can't figure out any viable workarounds.

2

There are 2 answers

0
David Sherret On

Looking at checker.ts, the unknown type:

var unknownType = createIntrinsicType(TypeFlags.Unknown, "unknown");

...is not exposed. I would recommend opening a PR in TypeScript's repo to add it to TypeChecker, as I believe they would accept it given the other methods found on there.

In the meantime, you can hackily get it by doing the following:

const sourceFile = ts.createSourceFile("file.ts", "type Unknown = unknown", ts.ScriptTarget.ESNext, true);
const unknownType = checker.getTypeFromTypeNode(sourceFile.statements[0].type);
2
Jason Gore On

I posed the question incorrectly. I should have asked: "How can I confirm a Type is of type unknown?"

After consulting with the TypeScript team, the TS Compiler may have multiple definitions for intrinsic types internally, making the various get<Type> accessors inherently unstable.

The canonical way to check for intrinsic types like undefined and unknown is to compare Type.flags to TypeFlags.Undefined and TypeFlags.Unknown.