logoalt Hacker News

fainpulyesterday at 10:01 AM2 repliesview on HN

If it's an "array of strings AND numbers", then it should not be allowed to call the function with a string[], because those are different types.


Replies

saghmyesterday at 3:24 PM

That would be the sound way to do things, but it's also surprisingly common for arrays for some reason. It also doesn't get checked compile time in Java, although it does throw an exception because the arrays are type-enforced at runtime at least.

This compiles fine:

    class A {}

    class B1 extends A {}
    class B2 extends A {}

    public class MyClass {
        public static void main(String args[]) {
            A[] array = new B1[1];
            array[0] = new B2();
        }
    }
clownstrikelolyesterday at 2:17 PM

That’s barely scratching the surface.

In TypeScript the following is also valid:

class Something{

    value: Number
}

class SomethingElse{

    value: Number

    foo: String

    bar: SomeOtherThing[]
}

function AddSomething(v: Something)

{

    v.value += 1;
}

var ex = new SomethingElse{

    value: 3,

    foo: “TypeScript is fake types”,

    bar: []
};

AddSomething(ex);

Why does it work? Because in TypeScript as long as you have a “shape” that fits, it’s the “same type.”

Complete and utter insanity to me, to pretend there’s any real type checking, when types are entirely fake and made up.

show 1 reply