Closed
Description
TypeScript Version: nightly
Code
interface Test {
optional?: string;
}
function getProperty<K extends keyof Test>(t: Test, key: K): Test[K]|never {
if (t[key]) {
return t[key];
}
throw new Error('Value does not exist at key');
}
const a: string = getProperty({}, 'optional');
Target behavior:
The given function is coded such that it will always return a non-empty value, so it would be great if there were a way to make something like this compile. Is there a way to communicate the opposite of Partial<T>
, e.g. that we know Test[K]
will be non-empty?
Actual behavior:
error TS2322: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.