【问题标题】:Typescript: How to declare a dependant property?打字稿:如何声明依赖属性?
【发布时间】:2020-09-06 08:18:41
【问题描述】:

我正在尝试为 quadstore 库编写声明文件。该库定义了一个接受构造函数参数contextKey 的类。此参数的值确定方法参数上的字段名称。简化后,等效的 Typescript 将是:

interface MethodArg {
  a: string;
  b: string;
  <<Whatever is supplied as the value of contextKey or a default name>>: string;
}

class A {
  constructor(options?: {contextKey: string}) {}

  fn(arg: MethodArg) {...}
}

我如何声明MethodArg 的类型以表示第三个属性名称取决于赋予类构造函数的值(在声明文件中)?这可能吗?

【问题讨论】:

  • 泛型,可能

标签: typescript


【解决方案1】:

我认为这是不可能的,因为我理解构造函数参数的 value 是在运行时定义的,但是 MethodArg 的类型是在编译时定义的(?),所以后一个不能依赖于前者,但如果你更喜欢将值提升为类型参数(从而为编译时提供运行时信息),也许你可以这样做

type MethodArg<E extends keyof any> = {
  [T in E]: string;
} & { a: string; b: string };

class A<T extends string> {
  constructor(options?: { contextKey: T }) {}
  fn(arg: MethodArg<T>) {}
}

new A({ contextKey: "foo" }).fn({
  a: "100",
  b: "100",
  foo: "foo",
});


// not the following way
let foo: string = "123";
new A({ contextKey: foo }).fn({
  a: "100",
  b: "200",
});


【讨论】:

  • 谢谢,这很有趣!我同意用类型声明来表达是一件困难的事情。这是巧妙的,可能与我们能得到的一样接近
猜你喜欢
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 1970-01-01
相关资源
最近更新 更多