V
V
VladMokrousov2021-03-21 12:19:24
typescript
VladMokrousov, 2021-03-21 12:19:24

Why does Typescript consider a function argument to be valid?

Hi) The other day I encountered an interesting behavior of Typescript. I explicitly let know which interface the function argument should use. However, if you pass as an argument a value that will use an interface with additional fields, there will be no error. Why?
60570f6701c4a573673975.jpeg

interface IValidUser {
  name: string
}
interface IInvalidUser {
  name: string,
  age: number
}

const validUser: IValidUser = {name: 'Pavel'}
const invalidUser: IInvalidUser = {name: 'Nadya', age: 45}
  
const printUser = (user: IValidUser): void => {
  console.log(user)
}

printUser(validUser)
printUser(invalidUser)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vasily Bannikov, 2021-03-21
@VladMokrousov

Typescript uses structural typing, not nominative typing.
This means that it does not look at the names of the types, but at their content-structure.
And here, according to the structure, Invalid user expands Valid user.
You can fight this if you introduce some kind of incompatibility between these interfaces.
For example by adding a type field with some constant string knowledge

S
Sun_Day, 2021-03-21
@Sun_Day

As far as I remember, this is a known issue in typescript. There is no such type precision at the language design level, but what you would expect is in Flow.
Discussed here:
https://github.com/Microsoft/TypeScript/issues/12936
Almost 5 years, yes, look at the number of issues). I didn’t read the whole discussion, my hands don’t reach, but there seems to be progress.

A
Alexey Yarkov, 2021-03-21
@yarkov

Why not? Try to pass not a variable to the function, but the object itself - you will see the difference.
https://www.typescriptlang.org/play?#code/JYOwLgpg...
60571766537fe971401770.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question