[Typescript] 52. Medium - ObjectEntries
typescript Medium 52
2023-09-14 09:00:45 时间
Implement the type version of Object.entries
For example
interface Model {
name: string;
age: number;
locations: string[] | null;
}
type modelEntries = ObjectEntries<Model> // ['name', string] | ['age', number] | ['locations', string[] | null];
/* _____________ Your Code Here _____________ */
type ObjectEntries<T extends object> = {
[Key in keyof T]-?: Key extends keyof T ? [Key, T[Key] extends undefined ? undefined: Required<T>[Key]]: never
}[keyof T]
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
interface Model {
name: string
age: number
locations: string[] | null
}
type ModelEntries = ['name', string] | ['age', number] | ['locations', string[] | null]
type cases = [
Expect<Equal<ObjectEntries<Model>, ModelEntries>>,
Expect<Equal<ObjectEntries<Partial<Model>>, ModelEntries>>,
Expect<Equal<ObjectEntries<{ key?: undefined }>, ['key', undefined]>>,
Expect<Equal<ObjectEntries<{ key: undefined }>, ['key', undefined]>>,
]
type ObjectEntries<T extends object> = {
[Key in keyof T]-?: Key extends keyof T ? [Key, T[Key] extends undefined ? undefined: Exclude<T[Key], undefined>]: never
}[keyof T]
相关文章
- [Typescript] Represent Generics at the Lowest Level
- [Typescript] Get object prop value
- [Typescript] 95. Hard - Required Keys
- [Typescript] 92. Medium - PathParams
- [Typescript] 41. Medium - IsUnion
- [Typescript] 25. Medium - Trim Left
- [Typescript Challenges] 16. Medium - Omit
- [Typescript Challenges] 10. Medium - Include
- [Typescript] CommonJS Interop
- [Typescript] Using 'Pick' to create a sub-type from original type
- [Typescript] Installing Promise Type Definitions Using the lib Built-In Types
- [TypeScript] Create random integers in a given range
- [Typescript] Using Extract type until to get the value from Union type
- [Typescript] 132. Medium - Filter
- [Typescript] 105. Medium - Placeholder
- [!Typescript] 82. Medium - Combination
- [Typescript] 41. Medium - IsUnion
- [Typescript] 35. Medium - Absolute
- [Typescript challenge] 20. Medium - Chainable Options
- [Typescript v4.1] Template type literals
- TypeScript void 和 undefined 的区别