簡體   English   中英

如何在 TypeScript 中使用類型作為值? / 元類型

[英]How to use types as values in TypeScript? / Metatypes

我正在開發一個從數據源獲取記錄的組件。 該組件是用 TypeScript 編寫的,我不太習慣。

每條記錄都有一個鍵和記錄的值類型。 fetch 方法采用RecordDescriptor<Value>的實例,其通用參數Value確定方法的返回類型。

Swift中,我將使用以下代碼實現目標,並利用元類型:

struct RecordDescriptor<Value> {
    let key: String
    let valueType: Value.Type // `Value.Type` is a metatype, the type of a type
}

func fetchValue<Value>(for descriptor: RecordDescriptor<Value>) -> Value {
    // …
}

let intRecordDescriptor = RecordDescriptor(key: "int_record", valueType: Int.self)
// `Int.self` refers to the `Int` type itself, not an instance of `Int`

let intValue = fetchValue(for: intRecordDescriptor)

基本上,我可以專門化泛型參數Value而不使用類型的具體實例——只使用類型名稱本身。

如何在 TypeScript 中獲得相同的結果?

你不關心Metatypes類型的類型提示功能,你只關心它們的能力

訪問初始化程序或 class 或協議的其他 static 成員

這很簡單地拼寫為:

interface Newable {
    new(): any
}

type Constructable<T> =
  T extends Newable
    ? T
    : T extends (...args: any[]) => unknown
      ? T : never

type RecordDescriptor<T, Key extends string> = { key: Key }
  & (
    T extends Constructable<T>
      ? { transformation: T }
      // Replace this arm with `never`
      // to not allow scalars / non-classes like `boolean`
      : { transformation: (arg?: unknown) => T }
    )

用法是:

let descriptorN: RecordDescriptor<Number, "numbers"> = {
  key: "numbers",
  transformation: Number
}
let resultN: Number = descriptorN.transformation("123")


let descriptorF: RecordDescriptor<(a: string, b: boolean) => string | boolean, "crazy"> =
  { key: "crazy", transformation: (a, b) =>  b ? "hi" : a.length > 3 }
let resultF: string | boolean = descriptorF.transformation("hmm", true)

let rp: RecordDescriptor<boolean, "options"> =
  { key: "options", transformation: () => true }
let resultP: boolean = rp.transformation()

游樂場鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM