0

I'm just working with TypeScript for a few weeks, but I find it very interesting!

Are interfaces that are applied to an object also input validators? For example if I have a contact form or an API endpoint and I declare the type it produces - e. g.:

interface ContactFormData {
  firstName: string,
  lastName: string,
  shoeSize: number,
  favoriteBooks: Book[]
}

I know it only ensures the types of properties and can't protect against XSS.

Is it also possible to pass standard values with interfaces, assuming a property of an object which can also be "undefined" is empty?

1 Answer 1

4

Types don't exist at runtime and therefore no type can protect your application against anything at runtime.

Take the following code as an example.

const data = "" as any as ContactFormData;
data.favoriteBooks[0] // passes. but error at runtime

Following up is that interfaces are not "validators" they are structures, Typescript is structurally typed that means that any other type in your application that has the same structure as ContactFormData is assignable to ContactFormData, simiarly any type that is a super-set of ContactFormData is assignable to ContactFormData.

Any type coming from an API is essentially "any" or "unknown" you can attempt to type it coming in but realistically its a false sense of protection because if the API goes down, if the API changes undeneath you, or one of the many other ways an unexpected result could happen then your application will break at runtime.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.