简体   繁体   English

有没有办法动态键入 TypeScript 接口的部分?

[英]Is there a way to dynamically type section of a TypeScript interface?

I want to have a TypeScript object be extended by a type.我想让一个 TypeScript object 被一个类型扩展。 For example:例如:

interface BaseInterface<T> {
  staticA: string;
  staticB: number;
  dynamicA: T;
}

BaseInterface<SomeOtherInterfaceOrType>

When used like so, it should define dynamicA type as SomeOtherInterfaceOrType .像这样使用时,它应该将dynamicA类型定义为SomeOtherInterfaceOrType

How can this behaviour be achieved?如何实现这种行为? How can I create another interface that is of that type?如何创建另一个该类型的接口?

Type aliases are your friend: You can create type aliases using syntax similar to variable declaration. 类型别名是你的朋友:你可以使用类似于变量声明的语法来创建类型别名。 This way, you can permanently fix your generic interface to a concrete type, and this can be done an infinite amount of times, for any type matching T (in this case, because T isn't constrained - any type).通过这种方式,您可以将通用接口永久固定为具体类型,并且对于匹配 T 的任何类型(在这种情况下,因为 T 不受约束 - 任何类型),这可以进行无限次。 Generic types are just type/interface factories.通用类型只是类型/接口工厂。

interface BaseInterface<T> {
  staticA: string;
  staticB: number;
  dynamicA: T;
}

type ConstrainedToSymbol = BaseInterface<Symbol>;
// mostly equivalent interface fixing:
interface ConstrainedToNumber extends BaseInterface<number> {}

type ConstrainedToString = BaseInterface<string>;

function func(cbs: ConstrainedToString):string {
 return cbs.dynamicA // Always a string!
}

Check out this playground .看看这个游乐场

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

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