N. McA. N. McA. - 1 month ago 8
TypeScript Question

Strings are not type checked in Typescript?

Could somebody explain why the following code compiles in typescript, and ideally how to prevent it from doing so?

class Foo {}

function bar(f : Foo) {
console.log(f)
}

bar("lol wat?")


EDIT:
This is just a quick edit to explain why I ran into this problem, to hopefully save some future people some time.
I defined a type

type Message = MySubMessageType | SomeImportedConfigMessageType


SomeImportedConfigMessageType was allowed to be an empty object, and thus any method I defined taking one of my messages would take anything. Stay safe out there!

Answer

TypeScript is structurally typed.

You declare the method Bar to take an argument of type Foo.

Your type Foo does not contain any constraints other than that it's an object.

Strings are also objects, thus they are compatible with your type Foo.

There is currently no non-hacky way to get nominal typing in TypeScript, but if you are interested you might want to check out this github issue.

Comments