如何检查打字稿的 repl (ts-node) 中的类型?
How to examine a type in typescript's repl (ts-node)?
所以我输入了以下内容
type Duck = {
colors: string;
featheres: number;
}
type DuckProps = keyof Duck
我如何 examine/verify 例如 DuckProps
是有价值的:'colors' | 'feathers'
?
我似乎无法控制日志或使用它,因为它只会 return
[eval].ts:8:7 - error TS2693: 'DuckProps' only refers to a type, but is being used as a value here.
您如何通过 repl 与 typesript 特定构造(接口、类型等)进行交互?换句话说,当我输入 Duck 时。我希望出现这样的结果:
$ Duck
Duck<Typescript type> { color: string; feathers: number }
keyof Duck 不会给你类型,只会给你值,
你应该使用:
let duckProps = keyof Duck;
我假设您想要确保没有人会使用具有不存在的 属性 名称的类型 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
这里有一些 hack,但可以完成工作。使用 .type
命令,我们可以将我们感兴趣的类型强制转换为语句,并获取 ts-node
以显示与其关联的快速信息。
> type Duck = {
... colors: string;
... featheres: number;
... }
undefined
> type DuckProps = keyof Duck
undefined
> .type _ as DuckProps
type DuckProps = "colors" | "featheres"
警告: 这仅适用于末尾的命名类型。下面发生的是 .type
使用输入末尾的位置调用打字稿的 getQuickInfoAtPosition
。就像打字稿游乐场中的 ctrl 悬停一样,底部的灰线是除了一些文档之外还显示的内容。
这似乎是 ts-node 的一个有用功能,可能需要一个功能请求。
所以我输入了以下内容
type Duck = {
colors: string;
featheres: number;
}
type DuckProps = keyof Duck
我如何 examine/verify 例如 DuckProps
是有价值的:'colors' | 'feathers'
?
我似乎无法控制日志或使用它,因为它只会 return
[eval].ts:8:7 - error TS2693: 'DuckProps' only refers to a type, but is being used as a value here.
您如何通过 repl 与 typesript 特定构造(接口、类型等)进行交互?换句话说,当我输入 Duck 时。我希望出现这样的结果:
$ Duck
Duck<Typescript type> { color: string; feathers: number }
keyof Duck 不会给你类型,只会给你值, 你应该使用:
let duckProps = keyof Duck;
我假设您想要确保没有人会使用具有不存在的 属性 名称的类型 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
这里有一些 hack,但可以完成工作。使用 .type
命令,我们可以将我们感兴趣的类型强制转换为语句,并获取 ts-node
以显示与其关联的快速信息。
> type Duck = {
... colors: string;
... featheres: number;
... }
undefined
> type DuckProps = keyof Duck
undefined
> .type _ as DuckProps
type DuckProps = "colors" | "featheres"
警告: 这仅适用于末尾的命名类型。下面发生的是 .type
使用输入末尾的位置调用打字稿的 getQuickInfoAtPosition
。就像打字稿游乐场中的 ctrl 悬停一样,底部的灰线是除了一些文档之外还显示的内容。
这似乎是 ts-node 的一个有用功能,可能需要一个功能请求。