Skip to content

Error typeof type guards #20613

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ghost opened this issue Dec 11, 2017 · 9 comments
Closed

Error typeof type guards #20613

ghost opened this issue Dec 11, 2017 · 9 comments
Labels
Bug A bug in TypeScript Duplicate An existing issue was already created Fixed A PR has been merged for this issue

Comments

@ghost
Copy link

ghost commented Dec 11, 2017

export async function add(params: { [key: string]: string | string[] }): Promise<string> {
 if (!params.birthday || typeof params.birthday !== "string" || !Date.parse(params.birthday))
{
...
}
}

Get an Typscript Error on !Date.parse(params.birthday) because params.birthday can be a string or string []

Possible to make also object typeof recognize it as a type guard ?

@ghost
Copy link

ghost commented Dec 11, 2017

Duplicate of #17567
This actually works in typescript@next thanks to #19838.

@ghost ghost added Fixed A PR has been merged for this issue Duplicate An existing issue was already created Bug A bug in TypeScript labels Dec 11, 2017
@ghost
Copy link
Author

ghost commented Dec 12, 2017

I try the [email protected] => Not solve the issue.
Not certain you get the issue.
I make a motion on : "Luckily, you don’t need to abstract typeof x === "number" into its own function because TypeScript will recognize it as a type guard on its own. That means we could just write these checks inline."
From : https://www.typescriptlang.org/docs/handbook/advanced-types.html
This recognize seems to work on primitive but not on object like in my example : typeof params.birthday !== "string"

@ghost
Copy link

ghost commented Dec 12, 2017

Are you sure you installed it successfully? I don't see an error at Date.parse(params.birthday) when compiling with [email protected]. Could you check tsc -- version to make sure you're using the latest?

@ghost
Copy link
Author

ghost commented Dec 12, 2017

Yes : Version 2.7.0-dev.20171212
this is my example function :

export function test(params: ParsedUrlQuery): void {
    try {
        if (typeof params.birthday !== "string" || !Date.parse(params.birthday)) {
            throw (new AppError("Birthday invalid.", BAD_REQUEST));
        }
    } catch {
        console.log("So bad");
    }
}

and here my temporary patch:

export function test(params: ParsedUrlQuery): void {
    try {
        if (typeof params.birthday !== "string" || !Date.parse(params.birthday as string)) {
            throw (new AppError("Birthday invalid.", BAD_REQUEST));
        }
    } catch {
        console.log("So bad");
    }
}

and the : interface ParsedUrlQuery { [key: string]: string | string[]; }

@ghost
Copy link

ghost commented Dec 12, 2017

I don't get a compile error in this example:

interface ParsedUrlQuery { [key: string]: string | string[]; }
function test(params: ParsedUrlQuery): boolean {
    return typeof params.birthday !== "string" || !Date.parse(params.birthday);
}

Do you? If you do, what tsconfig settings do you have?

@ghost
Copy link
Author

ghost commented Dec 12, 2017


{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",
    /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs",
    /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": [
      "es2015"
    ],
    /* Specify library files to be included in the compilation:  */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    "declaration": false,
    /* Generates corresponding '.d.ts' file. */
    "sourceMap": false,
    /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./",
    /* Redirect output structure to the directory. */
    "rootDir": "./",
    /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "removeComments": true,
    /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    "importHelpers": true,
    /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    /* Strict Type-Checking Options */
    "strict": true,
    /* Enable all strict type-checking options. */
    "noImplicitAny": true,
    /* Raise error on expressions and declarations with an implied 'any' type. */
    "strictNullChecks": true,
    /* Enable strict null checks. */
    "noImplicitThis": true,
    /* Raise error on 'this' expressions with an implied 'any' type. */
    "alwaysStrict": true,
    /* Parse in strict mode and emit "use strict" for each source file. */
    /* Additional Checks */
    "noUnusedLocals": true,
    /* Report errors on unused locals. */
    "noUnusedParameters": true,
    /* Report errors on unused parameters. */
    "noImplicitReturns": true,
    /* Report error when not all code paths in function return a value. */
    "noFallthroughCasesInSwitch": true,
    /* Report errors for fallthrough cases in switch statement. */
    /* Module Resolution Options */
    "moduleResolution": "node",
    /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    "allowSyntheticDefaultImports": true,
    /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    /* Source Map Options */
    // "sourceRoot": "./",                    /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "./",                       /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
    /* Experimental Options */
    "experimentalDecorators": true,
    /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */
  },
  "compileOnSave": false,
  "exclude": [
    "./node_modules"
  ]
}

@ghost
Copy link

ghost commented Dec 12, 2017

Using that exact tsconfig.json, and a project with a single file containing the exact text from my above comment, I get no error when running tsc. My tsc --version is Version 2.7.0-dev.20171212.

@ghost
Copy link
Author

ghost commented Dec 12, 2017

Ok thanks. I will investigate. Maybe conflict with my TSlint.

@ghost
Copy link
Author

ghost commented Dec 13, 2017

Ok confirm the Version 2.7.0-dev.20171212 solved the issue. I had a conflict between global and local package in the last test. Thanks for your job!
For information the exact compile error in the 2.6.2 was : error TS2345: Argument of type 'string | string[]' is not assignable to parameter of type 'string'.
Type 'string[]' is not assignable to type 'string'.

@ghost ghost closed this as completed Dec 13, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
This issue was closed.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Bug A bug in TypeScript Duplicate An existing issue was already created Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

0 participants