假设我们有一种类型:
type A = {
a1?: string;
a2?: number;
a3?: boolean;
}以及用于自动完成的具有此类型的变量:
const b: A = {
a1: "test";
}b现在有了A类型,但我想推断出这种类型:
type B = {
a1: string;
}有可能吗?
我需要创建具有以下签名的函数:
type A = {
a1?: string;
a2?: number;
a3?: boolean;
}
const b = build<A>(() => {
return {
// autocompletion from type A should works
a1: string;
}
});b的类型应该是:
type B = {
a1: string;
}发布于 2022-08-29 14:14:04
将satisfies运算符合并到TS 4.9中,使用TS 4.9 (定于2022年11月)的简单方法是:
type A = {
a1?: string;
a2?: number;
a3?: boolean;
}
const b = {
a1: "test"
} satisfies A;请参见:
发布于 2022-08-29 09:21:55
当我正确理解你的问题时,你想要这样做
type A = {
a1?: string;
a2?: number;
a3?: boolean;
}
const b: A = {
a1: "test"
}
function identityCheck<T = never>() {
return <I>(input: I & T) => input as I;
}
const b1 = identityCheck<A>()({
a1: "test"
})
// now only a1 is shown in auto-complete
b1.a1发布于 2022-08-29 09:59:24
基于TmTron答案,我创建了一个基于类的解决方案,因为我不喜欢赛跑的样子:
class SomeBuilder<S = never> {
constructor() {}
build<T>(callback: () => S & T) {
return callback as () => T;
}
}https://stackoverflow.com/questions/73526153
复制相似问题