我想当属性键以目标字符串开头时,应从原始类型中过滤新的对象类型。
产地类型:
type Origin = {
a: string,
b: string,
_c: string,
_d: string,
}
Run Code Online (Sandbox Code Playgroud)
我想要的结果类型:
// type Result = SomethingWork<Origin, '_'>;
type Result = {
a: string,
b: string
};
Run Code Online (Sandbox Code Playgroud)
Origin 类型具有动态属性键。所以如果直接使用类型,这是不正确的'_c' | '_d'
Joo*_*nas 14
现在可以使用模板文字类型实现这一点
type FilterNotStartingWith<Set, Needle extends string> = Set extends `${Needle}${infer _X}` ? never : Set
Run Code Online (Sandbox Code Playgroud)
例子:
type Origin = {
a: string,
b: string,
_c: string,
_d: string,
}
type FilteredKeys = FilterNotStartingWith<keyof Origin, '_'>
type NewOrigin = Pick<Origin, FilteredKeys>
/*
type NewOrigin = {
a: string;
b: string;
}
*/
Run Code Online (Sandbox Code Playgroud)
我想对现有答案进行稍微简化。
type Origin = {
a: string,
b: string,
_c: string,
_d: string,
}
type OriginWithoutUnderscoreProps = Omit<Origin, `_${string}`>
/*
type OriginWithoutUnderscoreProps = {
a: string;
b: string;
}
*/
Run Code Online (Sandbox Code Playgroud)
包含的逆过程也有效。请注意,keyof Origin这里需要 ,因为对其第二个参数Pick有约束,而没有。keyofOmit
type OriginWithUnderscoreProps = Pick<Origin, keyof Origin & `_${string}`>
/*
type OriginWithUnderscoreProps = {
_c: string;
_d: string;
}
*/
Run Code Online (Sandbox Code Playgroud)
不能用前缀来做
但
import { ITSDiff, ITSPickMember } from 'ts-type';
export type Origin = {
a: string,
b: string,
_c: string,
_d: string,
}
export type Result = Pick<Origin, ITSDiff<keyof Origin, '_c' | '_d'>>
let a: Result;
a.a.padEnd(1)
a._c // err
Run Code Online (Sandbox Code Playgroud)
export type OriginOnlyHasPrefix = {
_c: string,
_d: string,
}
export type Result3 = Pick<Origin, ITSDiff<keyof Origin, keyof OriginOnlyHasPrefix>>
let a3: Result3;
a3.a.padEnd(1)
// @ts-ignore err when without @ts-ignore
a3._c;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3821 次 |
| 最近记录: |