-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Is this possible? Opposite of Partial Type #12578
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
You can use inference from homomorphic mapped types in #12528 to get a type that removes the for instance: interface Test {
optional?: string;
required: number;
}
type OptionalMap<T> = {
[P in keyof T]: T[P] | undefined;
};
function getProperty<T, K extends keyof T>(t: T, key: K): T[K] {
return t[key];
}
function getPropertyRemoveUndefined<T, K extends keyof T>(t: OptionalMap<T>, key: K): T[K] {
// Put it in a value, since `t[p]` is not narrowed only t.p which is not possible here
var value = t[key];
if (value) {
return value;
}
throw new Error('Value does not exist at key');
}
var t: Test = {required: 0};
var o1 = getProperty(t, 'optional'); // string | undefined
var r1 = getProperty(t, 'required'); // number
var o2 = getPropertyRemoveUndefined(t, 'optional'); // string
var r2 = getPropertyRemoveUndefined(t, 'required'); // number |
I just merged #12589 and now you can simply use the predefined interface Test {
optional?: string;
required: number;
}
function getProperty<T, K extends keyof T>(t: T, key: K): T[K] {
return t[key];
}
function getPropertyRemoveUndefined<T, K extends keyof T>(t: Partial<T>, key: K): T[K] {
// Put it in a value, since `t[p]` is not narrowed only t.p which is not possible here
var value = t[key];
if (value) {
return value;
}
throw new Error('Value does not exist at key');
}
var t: Test = {required: 0};
var o1 = getProperty(t, 'optional'); // string | undefined
var r1 = getProperty(t, 'required'); // number
var o2 = getPropertyRemoveUndefined(t, 'optional'); // string
var r2 = getPropertyRemoveUndefined(t, 'required'); // number |
@opensrcken BTW, I noticed that you used a union |
It works. And point taken on |
So I must write a function to get these opposite type ? |
TypeScript 2.8 introduces |
Uh oh!
There was an error while loading. Please reload this page.
TypeScript Version: nightly
Code
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 knowTest[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'.
The text was updated successfully, but these errors were encountered: