Answer the question
In order to leave comments, you need to log in
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?
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
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
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.
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...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question