question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Support custom typeof functions

See original GitHub issue

Search Terms

  • custom typeof
  • custom typeof function
  • custom type guard

Suggestion

When using a custom typeof‑like function, I’d like TypeScript compiler to be able to infer the correct type in the scope guarded by the custom typeof‑like function.

Use Cases

I need this to provide proper type information for the type function from Blissfuljs and similar projects.

The current approach requires defining the type(…) function as type(obj: any): string and then doing a type cast every time something is accessed within the if block:

/// <reference types="blissfuljs"/>
declare var something: any;
if ($.type(something) === "array") {
	(something as any[]).forEach(v => {/* stuff */})
}

Examples

type-func.d.ts
/**
 * @param obj The variable to check the type of.
 * @return The result of `typeof obj` or the class name in lowercase for objects.
 *         In the case of numbers, if the value is `NaN`, then the result is `nan`.
 */
declare function type(obj: null): "null";
declare function type(obj: undefined): "undefined";

// This is to ensure that the type system short-circuits when it encounters primitive types.
declare function type(obj: number): "number" | "nan";
declare function type(obj: string): "string";
declare function type(obj: symbol): "symbol";
declare function type(obj: boolean): "boolean";

// Needed to ensure proper return values when wrapper objects are used.
/* tslint:disable:ban-types */
declare function type(obj: number | Number): "number" | "nan";
declare function type(obj: string | String): "string";
declare function type(obj: symbol | Symbol): "symbol";
declare function type(obj: boolean | Boolean): "boolean";
declare function type(obj: Function): "function";
/* tslint:enable:ban-types */

declare function type(obj: any[]): "array";
declare function type(obj: RegExp): "regexp";
declare function type(obj: any): string;
export = type;

example.ts

import type = require("./type-func");
declare var something: any;

if (type(something) === "array") {
	// $ExpectType any[]
	something;
} else if (type(somthing) === "number") {
	// $ExpectType number
	something;
}

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. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript’s Design Goals.

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:1
  • Comments:13 (8 by maintainers)

github_iconTop GitHub Comments

5reactions
dragomirtitiancommented, Apr 2, 2019

@ExE-Boss There isn’t enough in the type system to know that 'regex' is tied to the Regex type, and overloads don’t seem like a good choice to encode this behavior . I would propose an extension to the type guard syntax. Add the capability to specify the return value when a parameter is of certain type

declare function type(obj: any): 
    obj is number? "number" | "nan" :
    obj is string ? "string":
    obj is symbol ? "symbol"

After ? you can have a literal type or a union of literal types. Omitting ? defaults to obj is T ? true: obj is Exclude<typeof obj, T>? false which is the current behavior.

</wacky-syntax-proposal >

2reactions
ExE-Bosscommented, Apr 1, 2019

Because I’m using a JavaScript library that doesn’t work that way: https://blissfuljs.com/docs.html#fn-type

Read more comments on GitHub >

github_iconTop Results From Across the Web

typeof - JavaScript - MDN Web Docs - Mozilla
Custom method that gets a more specific type​​ For greater specificity in checking types, here we present a custom type(value) function, which ...
Read more >
How To Create Custom Types in TypeScript - DigitalOcean
This tutorial will show you how to use custom types with ... In these cases, declaring your own type will help you address...
Read more >
Typescript: Check "typeof" against custom type - Stack Overflow
Short answer: You can't use typeof at runtime to check for interface types, which only exist at compile time.
Read more >
User-defined Type Guards in Typescript | by Slawek Plamowski
Type Guards are one of the key features of type-safe code. They allow you to narrow down the type of an object within...
Read more >
Chapter 2. Basic and custom types - TypeScript Quickly
Declaring variables with types, and using types in function declarations; Declaring type aliases with the type keyword; Declaring custom types with classes ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found