I have a simple react component.
typescript does not throw any error (which it should) when I use HTMLInputElement as useRef hook type and assign it to a div.
import { useRef } from "react"
export default function Box(){
const ref = useRef<HTMLInputElement>(null)
return <div ref={ref}>this is a div</div>
}
This is the codesandbox link where you can see it https://codesandbox.io/s/sleepy-galileo-27cb1y?file=/src/Box.tsx
Also i tried it in my vscode and the result was same.
I tried it on codesandbox and on my vscode and had the same result. I expect ts to throw error when using HTMLInputElement type ref and assigning it to a div.
Because
HTMLInputElementis a assignable toHTMLDivElement.This feels wrong, but remember that Typescript is structural, not nominal. This means that if a value has all properties of an interface, than it may be treated as that interface.
It looks like
HTMLDivElementhas this type:And
HTMLInputElementhas this type:The important thing to note is that the tag name
"div"vs"input"is not part of the type, and that theHTMLInputElementtype has every property that is required by theHTMLDivElementtype. So Typescript allows that assignment.It's also worth noting that if you do something like this, it will be a type error: