[英]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.