[英]In TypeScript how do I use index type query operator to get only subset of type's properties?
I have the following code:我有以下代码:
var o = { x: 5, y: 6, z: 'hi' }
type OnlyNumberProps = keyof typeof o; // 'x' | 'y' | 'z' I want it somehow to be 'x' | 'y'
var p : OnlyNumberProps = 'z' // How to get error here ?
var z : OnlyNumberProps = 'x' // And OK here ?
How can I filter the type OnlyNumberProps
to contain only names of number properties of object o
?如何过滤类型
OnlyNumberProps
以仅包含对象o
的数字属性的名称?
This is not possible to do.这是不可能的。
The closest you can get using mapped types is this:使用映射类型可以获得的最接近的是:
var o = { x: 5, y: 6, z: 'hi' }
type TypeOfO = typeof o;
type OnlyNumber = {
[P in keyof TypeOfO]: number;
}
But then OnlyNumber
will be:但是
OnlyNumber
将是:
type OnlyNumbers = { x: number; y: number; z: number; }
Which isn't what you're looking for.这不是你要找的。
There's no way to filter the keys.无法过滤密钥。
I think this is a possible solution:我认为这是一个可能的解决方案:
var o = { x: 5, y: 6, z: 'hi' }
type PropertyNames<T> = {
[k in keyof T]: T[k] extends number ? k : never
} [keyof T]
type Properties<T> = Pick<T, PropertyNames<T>>;
let c1: Properties<typeof o> = {x: 1, y: 3} //ok
let c2: Properties<typeof o> = {x: 1, y: 3, z: "huhu"} //error
let c3: Properties<typeof o> = {} //error
let c4: Properties<typeof o> = {huhu: true} //error
step by step explanation:一步一步的解释:
typeof o
resolves to {x: number, y: number, z: string}
typeof o
解析为{x: number, y: number, z: string}
type Foo<T> = {
[k in keyof T]:k
}
supplied with the type argument Foo<typeof o>
resolves to {x: "x", y: "y", z: "z"}
提供类型参数
Foo<typeof o>
解析为{x: "x", y: "y", z: "z"}
type Foo<T> = {
[k in keyof T]:T[k]
}
supplied with the type argument Foo<typeof o>
resolves to {x: number, y: number, z: string}
提供类型参数
Foo<typeof o>
解析为{x: number, y: number, z: string}
We use the conditional type T[k] extends number? k: never
我们使用条件类型
T[k] extends number? k: never
T[k] extends number? k: never
. T[k] extends number? k: never
。 If T[k]
resolves to a number the conditional type resolves to the key of T as a string literal type otherwise to never.如果
T[k]
解析为数字,则条件类型解析为 T 的键作为字符串文字类型,否则为 never。
A type like像这样的类型
type Foo<T> = {
[k in keyof T]:T[k] extends number ? k : never
}
supplied with the type argument Foo<typeof o>
resolves to {x: "x", y: "y", z: never}
提供类型参数
Foo<typeof o>
解析为{x: "x", y: "y", z: never}
type PropertyNames<T> = {
[k in keyof T]: T[k] extends number ? k : never
} [keyof T]
supplied with the type argument PropertyNames<typeof o>
resolves to "x"|"y"|never
which is the same as "x"|"y"
提供类型参数
PropertyNames<typeof o>
解析为"x"|"y"|never
与"x"|"y"
相同
Pick<typeof o, "x"|"y">
resolves to {x: number, y: number}
解析为
{x: number, y: number}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.