I have a function that is intended to either return a value of IDBValidKey or something converted to IDBValidKey. If I write the function using the ternary operator it works fine but it causes a compiler error if I write it as an if-else statement:
interface IDBValidKeyConvertible<TConverted extends IDBValidKey> {
convertToIDBValidKey: () => TConverted;
}
function isIDBValidKeyConvertible<TConvertedDBValidKey extends IDBValidKey>(object: unknown): object is IDBValidKeyConvertible<TConvertedDBValidKey> {
return typeof((object as IDBValidKeyConvertible<TConvertedDBValidKey>).convertToIDBValidKey) === "function";
}
type IDBValidKeyOrConverted<TKey> = TKey extends IDBValidKeyConvertible<infer TConvertedKey> ? TConvertedKey : TKey;
function getKeyOrConvertedKey<TKey extends IDBValidKey | IDBValidKeyConvertible<any>>(input: TKey): IDBValidKeyOrConverted<TKey> {
if (isIDBValidKeyConvertible<IDBValidKeyOrConverted<TKey>>(input)) {
return input.convertToIDBValidKey();
} else {
return input;
}
}
function getKeyOrConvertedKeyTernary<TKey extends IDBValidKey | IDBValidKeyConvertible<any>>(input: TKey): IDBValidKeyOrConverted<TKey> {
return (isIDBValidKeyConvertible<IDBValidKeyOrConverted<TKey>>(input)) ? input.convertToIDBValidKey() : input;
}
getKeyOrConvertedKeyTernary produces no errors but the else block of getKeyOrConvertedKey yields this error:
Type 'TKey' is not assignable to type 'IDBValidKeyOrConverted<TKey>'.
Type 'string | number | Date | ArrayBufferView | ArrayBuffer | IDBArrayKey | IDBValidKeyConvertible<any>' is not assignable to type 'IDBValidKeyOrConverted<TKey>'.
Type 'string' is not assignable to type 'IDBValidKeyOrConverted<TKey>'.
Aren't the ternary operator and the if-else statement equivalent?
Thanks!
ReturnStatement > ConditionalExpression > Binary Expression > ...versusIfStatement > ((BinaryExpression > ...) + (Block ReturnStatement) + (Block ReturnStatement). Having said that, I'm not sure why that would cause this result... Great question!