简体   繁体   English

TypeScript:自动完成但禁用推断

[英]TypeScript: autocomplete but disable inferring

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: b现在有类型A ,但我想推断这种类型:

type B = {
  a1: string;
}

Is it possible?可能吗?


I need to create function with signature like this:我需要用这样的签名创建 function:

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: b的类型应该是:

type B = {
  a1: string;
}

When I understood your question right, you want to to this当我正确理解你的问题时,你想要这个

Playground Exmaple : 游乐场示例

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

see also: Is there a way to use a typescript interface with optional keys, but then concretize that the keys are there?另请参阅:有没有办法将 typescript 接口与可选键一起使用,然后具体化键是否存在?

With satisfies operator merged into TS 4.9, the straightforward approach with TS 4.9 (slated for November 2022) is:satisfies运算符合并到 TS 4.9 后,使用 TS 4.9(计划于 2022 年 11 月发布)的直接方法是:

type A = {
  a1?: string;
  a2?: number;
  a3?: boolean;
}

const b = {
  a1: "test"
} satisfies A;

See:看:

Based on TmTron answer I created a class based solution cuz I don't like how currying looks:基于 TmTron 的回答,我创建了一个基于 class 的解决方案,因为我不喜欢 currying 的样子:

class SomeBuilder<S = never> {
  constructor() {}

  build<T>(callback: () => S & T) {
    return callback as () => T;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM