TypeScript Equal custom type All In One
TypeScript Equal custom type All In One
Equal
import type { Equal, Expect } from '@type-challenges/utils'
// (alias) type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : false
demos
type GetReadonlyKeys<T> = keyof {[Key in keyof T as Equal<Pick<T, Key>, Readonly<Pick<T, Key>>> extends true ? Key : never]: Key}
/*
5 - 获取只读字段
#地狱 #utils #object-keys
### 题目
实现泛型`GetReadonlyKeys<T>`,`GetReadonlyKeys<T>`返回由对象 T 所有 只读属性 的键组成的 联合类型。
例如
/`/`/`ts
interface Todo {
readonly title: string
readonly description: string
completed: boolean
}
type Keys = GetReadonlyKeys<Todo> // expected to be "title" | "description"
/`/`/`
*/
// type GetReadonlyKeys<T> = any;
type GetReadonlyKeys<T> = keyof {[Key in keyof T as Equal<Pick<T, Key>, Readonly<Pick<T, Key>>> extends true ? Key : never]: Key}
// 测试用例
import type { Equal, Expect } from '@type-challenges/utils'
// (alias) type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : false
interface Todo1 {
readonly title: string
description: string
completed: boolean
}
interface Todo2 {
readonly title: string
readonly description: string
completed?: boolean
}
type cases = [
Expect<Equal<'title', GetReadonlyKeys<Todo1>>>,
Expect<Equal<'title' | 'description', GetReadonlyKeys<Todo2>>>,
]
https://www.typescriptlang.org/play
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://github.com/xgqfrms/developer-mind-mapping/blob/main/todos/chrome-tabs.md#typescript
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17197944.html
未经授权禁止转载,违者必究!