I want to return an object when I have a certain prop in the parameter of my function, and a string when not.
I can't use functions overloads because it is used in a type that is shared with React components, in React.useCallback.
I tried:
type FileType = {
name: string
content: string
}
// This is a type that I use in many part of my code. I would like the result of onSave to depend on the props it receive
type Props = {
onSave: <T extends FileType | undefined>(data: {
id: string
file: T
}) => T extends FileType ? FileType : string
}
const isFile = (o: unknown): o is FileType => {
return o !== undefined
}
// Here you can read the error
const insert: Props['onSave'] = prop => isFile(prop.file) ? prop.file : prop.id)
// Here is how the function is written in my code. But React doesn't exist in this playground
// const insert = React.useCallback<Props['onSave']>(prop => isFile(prop.file) ? prop.file : prop.id, [])
the error:
Type 'string | (T & FileType)' is not assignable to type 'T extends FileType ? FileType : string'.
Type 'string' is not assignable to type 'T extends FileType ? FileType : string'.
Playground Link: Provided