打字稿理解类型定义

时间:2021-06-28 10:52:28

标签: typescript

我是打字稿的新手并试图理解以下代码 有人可以帮忙吗,如果有什么好的课程/书来学习打字稿

type ConfigFactoryReturnValue =
  | Record<string, any>
  | Promise<Record<string, any>>;

export type ConfigFactory<
  T extends ConfigFactoryReturnValue = ConfigFactoryReturnValue
> = () => T;

2 个答案:

答案 0 :(得分:2)

尽管您的问题有点开放性和广泛性,但我会尽量提供有关您共享的代码的一些信息。

// The type keyword is used to define a type, for example
type MyCustomType = string;

// Record<K, T> is a Utility type for handling objects.
// Record defines the type of key:value pair.

// This means that MyRecord is an object whose keys are string and can have any value
type MyRecord = Record<string, any>;

// Promise is used to determine a Promise type, which means a method which returns a Promise
// Promise<T> is the syntax in which T determines the type of returned value when promise is resolved

// ConfigFactoryReturnValue is a Type which can be an object of type string:any or promise<Object<string, any>>
type ConfigFactoryReturnValue = Record<string, any> | Promise<Record<string, any>>;

// The Type T extends ConfigFactoryReturnValue signifies that Generic type T must satisfy the type
// ConfigFactoryReturnValue i.e. along with other keys it should have keys defined in ConfigFactoryReturnValue
export type ConfigFactory<T extends ConfigFactoryReturnValue> = () => T;

就 Typescript 课程/书籍而言,Udemy、Coursera 等平台上有大量在线课程。

答案 1 :(得分:1)

第一个块组合在 type aliasunion type 之间,这意味着您定义了自己的数据类型名称 ConfigFactoryReturnValue,该数据类型可以是 Record<string, any> 或 {{1} }

Promise<Record<string, any>>

第二个块结合了 type ConfigFactoryReturnValue = | Record<string, any> | Promise<Record<string, any>>; 和 typescript 的 type alias 特性。 这意味着导出泛型类型的 generics

alias type 定义类型 <T extends ConfigFactoryReturnValue = ConfigFactoryReturnValue> 应该从 T 扩展或者是 ConfigFactoryReturnValue 的默认实例。

ConfigFactoryReturnValue