LppEdd
LppEdd

Reputation: 21104

Typescript declared type not respected

I'm new to Typescript, so this might be a dumb question.
I've got a function such as:

interface MyType {
   myField: string
   myOtherField: string
}

const myFunction = (input: MyType) => { ... }

I've noticed that this function is able to receive values which are not MyType, e.g. I've seen values such as MyType[] or even string.

Now, probably this happens because Typescript simply output Javascript code, which does not know about types at all.

Is there a way to enforce type checking and throw an Error if such mismatch happens?

Edit: for future reference see https://github.com/fabiandev/ts-runtime

Upvotes: 0

Views: 482

Answers (1)

Fenton
Fenton

Reputation: 250822

The types are checked by the TypeScript compiler and are erased during compilation.

While you are working within TypeScript, you get all of the checking that you expect:

interface MyType {
   myField: string
   myOtherField: string
}

const myFunction = (input: MyType) => {
    return input.myField;
};

// OK
myFunction({ myField: '', myOtherField: '' });

// NOT OK
myFunction([{ myField: '', myOtherField: '' }]);

But if you call your transpiled JavaScript from another JavaScript file at runtime there is no type checking. Type checking at runtime is not a feature of TypeScript.

TS* / Safer TypeScript

There was a brief initiative to create a runtime type safe compiler for TypeScript, but it didn't gain traction and hasn't been updated since 2014.

Upvotes: 1

Related Questions