This is correct - you don't know if the name key exists on your props object.
You have two options:
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 correctly warning you because an object which does not have the name key is not the same as an object where the name key is undefined. Imagine this:
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`)
}