Skip to content

Allow more constructs to work as type guards for unknown #25720

Open
@AlCalzone

Description

@AlCalzone

Search Terms

unknown type guard
Related: #24439 (comment), #25172

Suggestion

Currently, only a very limited set of type guards are able to narrow the new unknown type:

  • Array.isArray (because it is a typeguard for arg is any[]) and probably some more in the lib files
  • instanceof
  • self-written typeguards

However to make working with unknown types less awkward, I'd like to see a couple of other constructs being able to narrow the unknown type:

let x: unknown;
// Direct equality should narrow to the type we compare to
x === "1"; // should narrow x to string or the literal "1" type, similar for other types aswell

// All these should narrow x to {prop: any}
"prop" in x;
x.prop != null;
x.prop !== undefined;
typeof x.prop !== "undefined";

// typeof should work on properties of the unknown variable
typeof x.prop === "string"; // should narrow x to {prop: string}

Use Cases

Make unknown easier to work with!

// before, very verbose!
const x: unknown = undefined!;

function hasProp1(x: any): x is {prop1: any} {
	return "prop1" in x;
}
function hasProp2(x: any): x is {prop2: any} {
	return "prop2" in x;
}
// imagine doing this for many more properties

if (hasProp1(x)) {
	x.prop1;
	if (hasProp2(x)) {
		x.prop2;
	}
}

// ===========

// after, much more concise and less overhead
const x: unknown = undefined!;
if ("prop1" in x) {
	x.prop1;
	if ("prop2" in x) {
		x.prop2;
	}
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions