34
loading...
This website collects cookies to deliver better user experience
Vehicle -> Car
, because every Car is a Vehicle, but not every Vehicle is a Car.let parent: string = 'hello'
let child: 'hello' = 'hello'
child is assignable to parent, but parent is not assignable to child.
let parent: string = 'hello'
let child: 'hello' = 'hello'
// ✅ ok, as parent is the "wider" type
parent = child
// 🚨 Type 'string' is not assignable to type '"hello"'.(2322)
child = parent
any -> string -> 'hello'
let top: any = 'hello'
let parent: string = 'hello'
let child: 'hello' = 'hello'
// ✅ ok, as parent is the "wider" type
parent = child
// ✅ also fine
top = parent
let top: any = 'hello'
let parent: string = 'hello'
let child: 'hello' = 'hello'
// 🚨 Type 'string' is not assignable to type '"hello"'.(2322)
child = parent
// 🤯 no type error here
parent = top
Anything is assignable to unknown, but unknown isn’t assignable to anything but itself and any
let top: unknown = 'hello'
let parent: string = 'hello'
let child: 'hello' = 'hello'
// ✅ ok, as parent is the "wider" type
parent = child
// ✅ also fine
top = parent
// 🚨 Type 'string' is not assignable to type '"hello"'.(2322)
child = parent
// 🚨 Type 'unknown' is not assignable to type 'string'.(2322)
parent = top
let top: unknown = 'hello'
let parent: string = 'hello'
if (typeof top === 'string') {
// ✅ top is of type string now, so it's assignable to parent
parent = top
}
When a value is of type any, you can access any properties of it (which will in turn be of type any), call it like a function, assign it to (or from) a value of any type, or pretty much anything else that’s syntactically legal.
const dangerous: any = 5
// ✅ inferred to the number literal 5
const okay = 5
// 🚨 result is now `any`
const result = dangerous + okay
const dangerous2: any = { title: 'foo' }
const props = { hello: 'world' } as const
// 🚨 result2 is now `any` as well
const result2 = {
...dangerous2,
...props,
} as const
declare function myAnyUtil(input: Record<string, unknown>): any
function App(props: Props) {
// ❗️ no other prop is type checked anymore
return (
<button onClick="yes please" {...myAnyUtil(props)}>
click me
</button>
)
}
declare function myAnyUtil(input: Record<string, unknown>): any
function App(props: Props) {
return React.createElement(
'button',
{ onClick: 'yes please', ...myAnyUtil(props) },
'click me'
)
}
With any, you can do anything, but everything is better than any.