Typescript: String method is wrongly allowed as a type

Created on 10 Nov 2016  路  6Comments  路  Source: microsoft/TypeScript

TypeScript Version: nightly (2.1.0-dev.20161110)

Code

// @Filename: a.d.ts
declare const x: "foo".charCodeAt(0);

Expected behavior:

An error; probably a syntax error.

Actual behavior:

x is of type number -- the return type of charCodeAt.

DIscovered at https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12603#discussion_r87405841.

Bug

Most helpful comment

...did someone accidentally implement #6606?

interface String {
    typeof<T>(x: T): T
}

class C {
    foo() {
        var x: "".typeof(this.foo);
    }
}

var nodes = document.getElementsByTagName('li');
type ItemType = "".typeof(nodes.item(0));

All 6 comments

...did someone accidentally implement #6606?

interface String {
    typeof<T>(x: T): T
}

class C {
    foo() {
        var x: "".typeof(this.foo);
    }
}

var nodes = document.getElementsByTagName('li');
type ItemType = "".typeof(nodes.item(0));

This only happens when the type starts with a string literal, so it probably has something to do with string literal types.

Actually it works with numeric literals as well

interface Number {
    typeof<T>(x: T): T
}

class C {
    foo() {
        var x: 3.141592.typeof(this.foo);
    }
}

var nodes = document.getElementsByTagName('li');
type ItemType = 4..typeof(nodes.item(0));

Same with true and false:

interface Boolean {
    typeof<T>(x: T): T
}

class C {
    foo() {
        var x: false.typeof(this.foo);
    }
}

var nodes = document.getElementsByTagName('li');
type ItemType = true.typeof(nodes.item(0));

Can we leave this in the language until #6606 lands? It's fun. 馃槀 See https://github.com/Microsoft/TypeScript/issues/6606#issuecomment-320382890

@TheOtherSamP I'm sorry. While I love hacky terrible stuff that shouldn't work in the first place, I highly suggest you don't take a dependency on this in any serious manner. Last I tried, it already broke in a lot of the ways that make #6606 hard to implement anyway.

@DanielRosenwasser Okay, fine, I'll be good.

It's supposedly been in the language since at least November 2016, and I spotted it 2 hours before it got a PR. grumbles 馃槀

Was this page helpful?
0 / 5 - 0 ratings

Related issues

chanon picture chanon  路  138Comments

Gaelan picture Gaelan  路  231Comments

yortus picture yortus  路  157Comments

quantuminformation picture quantuminformation  路  273Comments

disshishkov picture disshishkov  路  224Comments