Issue
Suppose we have a type:
type A = {
a1?: string;
a2?: number;
a3?: boolean;
}
And a variable with this type for autocompletion:
const b: A = {
a1: "test";
}
b
now has type A
, but I want to infer this type:
type B = {
a1: string;
}
Is it possible?
I need to create function with signature like this:
type A = {
a1?: string;
a2?: number;
a3?: boolean;
}
const b = build<A>(() => {
return {
// autocompletion from type A should works
a1: string;
}
});
where type of b
should be:
type B = {
a1: string;
}
Solution
With satisfies
operator merged into TS 4.9, the straightforward approach with TS 4.9 (slated for November 2022) is:
type A = {
a1?: string;
a2?: number;
a3?: boolean;
}
const b = {
a1: "test"
} satisfies A;
See:
- "satisfies" operator to ensure an expression matches some type (feedback reset) #47920
- Typescript satisfies article
- Playground link
Answered By - Lesiak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.