Issue
I'm trying to create a function in typescript that returns an object which must extend a given interface, but i want the function to return the real type of the created object. The reason is that the object in the function might change in the future and i want to make sure it will always have the minimum props required in the interface.
example:
interface MustExtend {
a: string;
}
function myFunc() {
// I want to enforce res to extend type MustExtend
// right now it can be of type {something: 3} and compiler will allow it
const res = {a: 'hello', b: 2}
return res;
}
const c = myFunc(); // c should be of type {a: string, b: number}, or the more concrete type generated by method
EDIT:
I will try to clarify my question. I want the result type of the function to be inferred from the returned object without specifying the type of res
, since it's generated by many computations:
interface MustExtend {
a: string;
}
function myFunc() {
// i want to enforce res to extend type MustExtend
// right now it can be of type {something: 3} (no 'a' at all)
// and i want to make sure it exists
const res = {
a: 'hello',
b: 2,
// a million more properties here that can change over time
}
return res;
}
const c = myFunc(); // c should be of type {a: string, b: number, ...other props}
Solution
After some tinkering i found how to do it:
interface MustExtend {
a: string;
}
function myFunc(): typeof res extends MustExtend ? typeof res : never {
// i want to enforce res to extend type MustExtend
// right now it can be of type {something: 3} (no 'a' at all)
// and i want to make sure it exists
const res = {
a: 'hello',
b: 2,
// a million more properties here that can change over time
}
return res;
}
const c = myFunc(); // c should be of type {a: string, b: number, ...other props}
Apparently typescript can get the type of the object in method during compile time and use it in the method types. Using it this way i don't have to specify the type of res
in advance and also ensure that it has all the properties from the interface
Answered By - Jellof
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.