Structural subtyping equivalence in Typescript

52 Views Asked by At

In the function below, an object is being returned in the first function which typescript compiler complains about. While for the second function it doesnt complain. Why this difference?

    type  x = {
    name:string
}
type r = {
    name:string,
    age:number
}
//Invalid
function returnSomething():x{
  return {
      name:"abc",
      age:12
  }
}
//Valid
function returnSomething():x{
        let z:r ={
        name:"abc",
        age:12
    }
    return z
}
console.log(returnSomething())
0

There are 0 best solutions below