I'm learning typescript from a course on frontendmasters, and it says (from here)
An interface is a way of defining an object type. An “object type” can be thought of as, “an instance of a class could conceivably look like this”.
For example, string | number is not an object type, because it makes use of the union type operator.
But then I saw a react example (from somewhere else)
// Header.tsx
interface Props {
title: string | number
color?: string
}
function Header(props: Props) {
return <header style={{ color: props.color || "red" }}>{props.title}</header>
}
export default Header
// App.tsx
import Header from "./Header"
function App() {
return (
<div className="App">
<Header title="My Website" />
<Header title="Boo" color="blue" />
<Header title={12345} color="green" />
</div>
)
}
It uses |
in interface Props
, there's no error and it works. Have I misunderstood something?
CodePudding user response:
An "interface" defines the "shape of object", while an union type title: string | number
means, the property "title" is either a string
or number
, and so you can give title either a string or number value:
interface Props {
title: string | number
color?: string // this is optional
}
// example:
const myProps1: Props = {
title: "some_string" // string type
}
const title1 = myProps1.title // returns a string
const myProps2: Props = {
title: 10 // number type
}
const title2 = myProps2.title // returns a number
So in the React, this is expected:
<Header title="My Website" /> // optional property "color" omited <- ok
<Header title="Boo" color="blue" /> // pass string value to "title" <- ok
<Header title={12345} color="green" /> // pass number value to "title" <- ok
CodePudding user response:
I think I've found out what I misunderstood. From tektutorialshub
Type alias can give a name to a union type. In this example stringOrNumber is a name for the union type of string | number
type stringOrNumber = string | number
We cannot do that using the interface.
You can also create union types of complex types like objects or interfaces etc. (...)
So it's about the interface itself can't be an union type. But a property of the interface can be an union type. So what Mike wrote on his site is correct. I just need an example to understand it.