打字稿理解类型定义

问题描述

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

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

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

解决方法

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

// 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 等平台上有大量在线课程。

,

第一个块组合在 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...