如何在 TypeScript 的 REPL(ts-node)中檢查一個類型?
所以我已經輸入了以下內容
type Duck = {
colors: string;
featheres: number;
}
type DuckProps = keyof Duck
我如何檢查/驗證,例如 DuckProps 的值是 'colors' | 'feathers'?
我似乎無法使用 console log 或使用它,因為它只會返回
[eval].ts:8:7 - error TS2693: 'DuckProps' only refers to a type, but is being used as a value here.
你如何透過 REPL 與 TypeScript 特有的構造(interface、type 等)互動?換句話說,當我輸入 Duck.時,我期待會出現類似這樣的東西:
$鴨
Duck<Typescript type> { color: string; feathers: number }
答案#1
這裡有一點小技巧,但能達到目的。使用 .type 指令,我們可以將感興趣的類型強制轉換成一個語句,並讓 ts-node 顯示與之相關的快速資訊。
> type Duck = {
... colors: string;
... featheres: number;
... }
undefined
> type DuckProps = keyof Duck
undefined
> .type _ as DuckProps
type DuckProps = "colors" | "featheres"
注意:這只對結尾的具名類型有效。其底層的運作方式是,.type 會在輸入的結尾位置呼叫 TypeScript 的 getQuickInfoAtPosition。就像在 TypeScript Playground 中按住 Ctrl 懸停一樣,而底部的灰色線條就是除了相關文件說明之外所顯示的內容。
這似乎是 ts-node 的一個有用功能,可能值得提出功能請求。
答案#2
我假設你想確保沒有人會在不存在的屬性名稱上使用 Duck 類型。在下面的程式碼範例中,我檢查了該屬性確實存在於 Duck 上,並且它的類型正確:
type Duck = {
colors: string;
featheres: number;
}
function doStuff<T, P extends keyof T>(
property: P,
value: T[P],
obj: T) {
// Do something
}
const myDuck = {
colors: "red",
featheres: 123
};
doStuff('colors', 'red', myDuck);
doStuff('featheres', 100, myDuck);
doStuff('colors', 123, myDuck); // error: the value of the wrong type
doStuff('colours', 'red', myDuck); // error: misspelled prop name
