我在一個具有 JS/TS 混合支持的專案上作業我正在尋找一種方法來減少將 JS 字串常量包裝為 Typescript 型別時的代碼重復。
例如,我有日志型別的常量:
// logTypes.js
export const ERROR = 'error'
export const INFO = 'info'
重新匯出它們:
// constants.js
export * as LOG_TYPES from './logTypes.js'
現在我想為這個常量提供一個 TS 型別:
// types.d.ts
import { LOG_TYPES } from './constants'
export type LogType = ???
顯然,我可以像這樣宣告型別,這將起作用:
// type LogType = "error" | "info", excellent
export type LogType = typeof LOG_TYPES.INFO | typeof LOG_TYPES.ERROR
但我認為這是多余的,并且當有人需要擴展常量集時也會創建兩個可維護的點。
所以,實際上我想寫這樣的東西:
// Does not work as desired
// type LogType = any, meh
export type LogType = typeof LOG_TYPES[string]
我知道型別和值之間存在差異,但是匯入/匯出的這個特定部分應該是靜態可分析的,所以我認為應該有一種方法可以做到這一點,我不知道
uj5u.com熱心網友回復:
確實是這樣的想法,但typeof LOG_TYPES不能被string, 但是keyof typeof LOG_TYPES:
type LogType = typeof LOG_TYPES[keyof typeof LOG_TYPES]
// ^? "error" | "info"
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/517336.html
