3

I am new to typescript, i wrote code like below

export class RmdRequest {
    public amount: string;
    public age: number;
}

in my form i have like

in my component i have like below

 onSubmit(formValues:RmdRequest){ }

formValues is a object like below

{amount: 20, age: "Super Hot"}

If you see amount i have declared as string but passing as int. I was expecting this to throw out error of some sort. Am i doing something wrong for validation?

6
  • amount is a ngModel of a textbox?? Commented Jul 1, 2017 at 21:22
  • Yup. I can block it at form level. But the above code should break right? or am i doing something wrong? Commented Jul 1, 2017 at 21:28
  • What happens when you're submitting it? Commented Jul 1, 2017 at 21:33
  • No error. It goes ahead and makes a service call. Which should not happen ideally. Commented Jul 1, 2017 at 21:35
  • Is amount really a number then? If it is coming from a textbox, it will be a string. Commented Jul 1, 2017 at 21:59

1 Answer 1

2

The types you add compile-time only and are erased by the TypeScript compiler at runtime so no type-checking is enforced at runtime. Here's what your code method looks like at runtime after compilation:

onSubmit(formValues) {
}

If you want to do actual validation on your form inputs, there are many options listed in the official documentation.

Sign up to request clarification or add additional context in comments.

5 Comments

I have done that. Say different scenario where in i need to validate the response coming from REST api with above method. Is that also not possible??
Not possible with TypeScript. You can only do compile-time type checking with TypeScript.
offering.solutions/blog/articles/2016/02/01/… Here if u see public Update = (id: number, itemToUpdate: MyTypedItem) itemToUpdate type checking does not happen at all?
Learn what? TypeScript? The official documentation would be a good place to start.
In your example, the itemToUpdate param will be validated only at compile time, but there is no guarantee that itemToUpdate will be of MyTypedItem at runtime.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.