所以我输入了以下内容
type Duck = {
colors: string;
featheres: number;
}
type DuckProps = keyof Duck 如何检查/验证例如DuckProps是否有价值:'colors' | 'feathers'
我似乎无法控制日志或使用它,因为它只会返回
[eval].ts:8:7 - error TS2693: 'DuckProps' only refers to a type, but is being used as a value here.如何与特定于类型的构造(接口、类型等)交互?通过爬行?换句话说,当我打鸭子的时候。我希望会有这样的事情出现:
$ Duck
Duck<Typescript type> { color: string; feathers: number }发布于 2019-04-20 21:03:53
这是一个小问题,但要把工作做好。使用.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节点的一个有用的特性,并且可能需要一个特性请求。
发布于 2019-04-19 13:10:38
键盘鸭子不会给你一个类型,只是价值,你应该使用:
设duckProps =鸭键;
发布于 2019-04-19 13:42:18
我假设您希望确保没有人使用不存在属性名的类型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 namehttps://stackoverflow.com/questions/55762315
复制相似问题