如何在typescript';s repl(ts节点)?
因此,我输入了以下内容如何在typescript';s repl(ts节点)?,typescript,ts-node,Typescript,Ts Node,因此,我输入了以下内容 type Duck = { colors: string; featheres: number; } type DuckProps = keyof Duck 我如何检查/验证例如DuckProps是否有价值:“颜色”|“羽毛” 我似乎无法控制台日志或使用它,因为它将返回 [eval].ts:8:7 - error TS2693: 'DuckProps' only refers to a type, but is being used as a val
type Duck = {
colors: string;
featheres: number;
}
type DuckProps = keyof Duck
我如何检查/验证例如DuckProps
是否有价值:“颜色”|“羽毛”
我似乎无法控制台日志或使用它,因为它将返回
[eval].ts:8:7 - error TS2693: 'DuckProps' only refers to a type, but is being used as a value here.
您如何通过repl与类型IPT特定的构造(接口、类型等)交互?换句话说,当我输入Duck时。我预计会出现这样的情况:
$Duck
Duck{颜色:字符串;羽毛:数字}
keyof Duck不会给你一个类型,只会给你一个值,
你应使用:
让duckProps=鸭子的钥匙 我假设您希望确保没有人使用不存在属性名的类型
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
type Duck={
颜色:字符串;
特征:数量;
}
函数doStuff(
财产:P,
值:T[P],
obj:T){
//做点什么
}
常数myDuck={
颜色:“红色”,
羽毛:123
};
多斯塔夫(“颜色”、“红色”、“myDuck”);
多斯塔夫('featheres',100,myDuck);
多斯塔夫('colors',123,myDuck);//错误:错误类型的值
多斯塔夫(‘颜色’、‘红色’、‘我的鸭子);//错误:拼写错误的道具名称
这里有点麻烦,但可以完成任务。使用.type
命令,我们可以将感兴趣的类型强制转换为语句,并获取ts节点
,以显示与其关联的快速信息
>类型Duck={
…颜色:字符串;
…特征:数字;
... }
未定义
>DuckProps类型=Duck的键
未定义
>.键入uu作为DuckProps
键入DuckProps=“colors”|“featheres”
注意事项:这仅适用于末尾的命名类型。下面发生的是.type
调用typescript的getQuickInfoAtPosition
,其位置位于输入的末尾。就像在typescript游乐场中按住ctrl键一样,除了一些文档之外,还显示了底部的灰线
这似乎是来自ts节点的一个有用的特性,可能需要一个特性请求。不完全是这样,我想
repl
并从命令行获得关于类型的反馈。所以当我输入Duck时。我希望有这样的东西出现:鸭子{颜色:线;羽毛:数字}不错!请注意,如果DuckProps不是什么东西,命令行将显示any
。谢谢
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