Skip to content

type predicate not working when imported via deno.json file #33198

@johndeighan

Description

@johndeighan

$ deno --version
deno 2.7.11 (stable, release, x86_64-pc-windows-msvc)
v8 14.7.173.7-rusty
typescript 5.9.2

I have a type predicate named isString(), defined in file src/lib/datatypes2.ts as:

export const isString = (x: unknown): x is string => {

	return (typeof x === 'string') || (x instanceof String)
}

Here is my script (in file src/temp/temp.ts:

import {yellow} from '@std/fmt/colors'
import {isString} from 'datatypes2'
// import {isString} from '../lib/datatypes2.lib.ts'

// ----------------------------------------------------

const trace = (x: unknown): void => {

		if (isString(x)) {
			console.log(yellow(x))
		}
	return
}

This version of the script fails when I run deno check src/temp/temp.ts, with the error:
TS2345 [ERROR]: Argument of type 'unknown' is not assignable to parameter of type 'string'.
console.log(yellow(x))
However, if I import the function isString directly from the file, i.e. switch the comment marker // from the third line to the second line, there is no error.
(FYI, my current directory is at c:/Users/johnd/mapper)

Here is my deno.json file (I think only the value for imports.datatypes2 is relevant):

{
	"tasks": {
		"dev": "deno run --watch main.ts"
		},
	"imports": {
		"@std/assert": "jsr:@std/assert@1",
		"@std/fmt/colors": "jsr:@std/fmt/colors",
		"@std/path": "jsr:@std/path",
		"@std/fmt/printf": "jsr:@std/fmt/printf",
		"npm-uglify-js": "npm:uglify-js",

		"base-utils": "c:/Users/johnd/mapper/src/lib/base-utils.lib.ts",
		"croak": "c:/Users/johnd/mapper/src/lib/croak.lib.ts",
		"datatypes": "c:/Users/johnd/mapper/src/lib/datatypes.lib.ts"
		"datatypes2": "c:/Users/johnd/mapper/src/lib/datatypes2.lib.ts"
		}
	}

Things I've tried:

  1. I prefer to define functions as constants, using lambda notation, but I've also tried this version with the same results:
import {yellow} from '@std/fmt/colors'
// import {isString} from 'datatypes2'
import {isString} from '../lib/datatypes2.lib.ts'

// ----------------------------------------------------

function trace(x: unknown): void {

		if (isString(x)) {
			console.log(yellow(x))
		}
	return
}

I've also used the zed editor to hover over the value x in the expression console.log(yellow(x)) and depending on which way I import the function, it will show the type of x to be either unknown or string. I assume the same would happen with vscode.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions