It is important to consider that you may not know if the name
key exists on the props
object.
You have a couple of choices:
1
function foo(props: A | B): string | undefined {
if ('name' in props) {
return props.name
}
}
2.
interface A {
name: string
age?: undefined
}
interface B {
name?: undefined
age: number
}
function foo(props: A | B): string | undefined {
return props.name
}
Why?
Typescript is alerting you because an object missing the name
key is different from an object where the name
key is undefined. Consider this scenario:
const a = {
// name is missing
age: 1
}
const b = {
name: 'test',
age: undefined
}
Object.keys(a) == ['age']
Object.keys(b) == ['name', 'age']
if ('age' in b) {
console.log('this is true')
}
if ('name' in a) {
throw new Error(`This is false`)
}