Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce the .readonly() method #117

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,22 @@ type Person = {name: string; age: number}
expectTypeOf<Person>().omit<'name'>().toEqualTypeOf<{age: number}>()
```

Use `.readonly` to create a `readonly` version of a type:

```typescript
type Post = {title: string; content: string}

expectTypeOf<Post>().readonly().toEqualTypeOf<Readonly<Post>>()
```

`.readonly` can make specific properties `readonly`:

```typescript
type Post = {title: string; content: string}

expectTypeOf<Post>().readonly('title').toEqualTypeOf<{readonly title: string; content: string}>()
```

Make assertions about object properties:

```typescript
Expand Down
92 changes: 91 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import type {
OverloadReturnTypes,
OverloadsNarrowedByParameters,
} from './overloads'
import type {StrictEqualUsingTSInternalIdenticalToOperator, AValue, MismatchArgs, Extends} from './utils'
import type {StrictEqualUsingTSInternalIdenticalToOperator, AValue, MismatchArgs, Extends, SetReadonly} from './utils'

export * from './branding' // backcompat, consider removing in next major version
export * from './utils' // backcompat, consider removing in next major version
Expand Down Expand Up @@ -654,6 +654,95 @@ export interface BaseExpectTypeOf<Actual, Options extends {positive: boolean}> {
keyToOmit?: KeyToOmit,
) => ExpectTypeOf<Omit<Actual, KeyToOmit>, Options>

/**
* Converts specified properties of an object to `readonly`.
* If no properties are specified, it defaults
* to making all properties `readonly`, similar to the native
* TypeScript {@linkcode Readonly} utility type.
*
* @example
* <caption>#### Make all properties `readonly` (default behavior)</caption>
*
* ```ts
* import { expectTypeOf } from 'expect-type'
*
* type Post = {
* title: string
* content: string
* }
*
* expectTypeOf<Post>().readonly().toEqualTypeOf<Readonly<Post>>()
* ```
*
* @example
* <caption>#### Make specific properties `readonly`</caption>
*
* ```ts
* import { expectTypeOf } from 'expect-type'
*
* type Post = {
* title: string
* content: string
* }
*
* expectTypeOf<Post>()
* .readonly('title')
* .toEqualTypeOf<{ readonly title: string; content: string }>()
* ```
*
* @param propertiesToMakeReadonly - The specific properties of the {@linkcode Actual} type to be made `readonly`. If omitted, all properties will be made `readonly`, behaving like the TypeScript {@linkcode Readonly} utility type.
* @returns the type with the specified properties made `readonly`. If no properties are specified, all properties will be made `readonly`, behaving like the TypeScript {@linkcode Readonly} utility.
*
* @template PropertiesToMakeReadonly - The keys of the __`Actual`__ type to be made `readonly`. Defaults to `never`, meaning no specific properties are targeted unless explicitly defined.
*
* @since 1.0.0
*/
readonly<PropertiesToMakeReadonly extends keyof Actual>(
propertiesToMakeReadonly: PropertiesToMakeReadonly,
): ExpectTypeOf<SetReadonly<Actual, PropertiesToMakeReadonly>, Options>

/**
* Converts specified properties of an object to `readonly`.
* If no properties are specified, it defaults
* to making all properties `readonly`, similar to the native
* TypeScript {@linkcode Readonly} utility type.
*
* @example
* <caption>#### Make all properties `readonly` (default behavior)</caption>
*
* ```ts
* import { expectTypeOf } from 'expect-type'
*
* type Post = {
* title: string
* content: string
* }
*
* expectTypeOf<Post>().readonly().toEqualTypeOf<Readonly<Post>>()
* ```
*
* @example
* <caption>#### Make specific properties `readonly`</caption>
*
* ```ts
* import { expectTypeOf } from 'expect-type'
*
* type Post = {
* title: string
* content: string
* }
*
* expectTypeOf<Post>()
* .readonly('title')
* .toEqualTypeOf<{ readonly title: string; content: string }>()
* ```
*
* @returns the type with the specified properties made `readonly`. If no properties are specified, all properties will be made `readonly`, behaving like the TypeScript {@linkcode Readonly} utility.
*
* @since 1.0.0
*/
readonly(): ExpectTypeOf<Readonly<Actual>, Options>

/**
* Extracts a certain function argument with `.parameter(number)` call to
* perform other assertions on it.
Expand Down Expand Up @@ -916,6 +1005,7 @@ export const expectTypeOf: _ExpectTypeOf = <Actual>(
exclude: expectTypeOf,
pick: expectTypeOf,
omit: expectTypeOf,
readonly: expectTypeOf,
toHaveProperty: expectTypeOf,
parameter: expectTypeOf,
}
Expand Down
128 changes: 127 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ type ReadonlyEquivalent<X, Y> = Extends<
/**
* Checks if one type extends another. Note: this is not quite the same as `Left extends Right` because:
* 1. If either type is `never`, the result is `true` iff the other type is also `never`.
* 2. Types are wrapped in a 1-tuple so that union types are not distributed - instead we consider `string | number` to _not_ extend `number`. If we used `Left extends Right` directly you would get `Extends<string | number, number>` => `false | true` => `boolean`.
* 2. Types are wrapped in a 1-tuple so that union types are not distributed - instead we consider `string | number` to _not_ extend `number`. If we used `Left extends Right` directly you would get `Extends<string | number, number>` =\> `false | true` =\> `boolean`.
*/
export type Extends<Left, Right> = IsNever<Left> extends true ? IsNever<Right> : [Left] extends [Right] ? true : false

Expand Down Expand Up @@ -227,3 +227,129 @@ export type TuplifyUnion<Union, LastElement = LastOf<Union>> =
* Convert a union like `1 | 2 | 3` to a tuple like `[1, 2, 3]`.
*/
export type UnionToTuple<Union> = TuplifyUnion<Union>

/**
* An alias for type `{}`. Represents any value that is
* not `null` or `undefined`. It is mostly used for semantic purposes
* to help distinguish between an empty object type and `{}` as
* they are not the same.
*
* @example
*
* ```ts
* import { expectTypeOf } from 'expect-type'
*
* expectTypeOf(42).toMatchTypeOf<AnyNonNullishValue>()
*
* expectTypeOf('Hello').toMatchTypeOf<AnyNonNullishValue>()
*
* // Results in [TS2322 Error]: Type 'null' is not assignable to type '{}'.
* expectTypeOf(null).not.toMatchTypeOf<AnyNonNullishValue>()
*
* // Results in [TS2322 Error]: Type 'undefined' is not assignable to type '{}'.
* expectTypeOf(undefined).not.toMatchTypeOf<AnyNonNullishValue>()
* ```
*
* @since 1.0.0
* @internal
*/
type AnyNonNullishValue = NonNullable<unknown>

/**
* A utility type that represents any function with any number of arguments
* and any return type.
*
* @example
*
* ```ts
* const log: AnyFunction = (...args: any[]) => console.log(...args)
*
* const sum = ((a: number, b: number): number => a + b) satisfies AnyFunction
* ```
*
* @since 1.0.0
* @internal
*/
type AnyFunction = (...args: any[]) => any

/**
* Useful to flatten the type output to improve type hints shown in editors.
* And also to transform an `interface` into a `type` alias to aide
* with assignability and portability.
*
* @example
* <caption>#### Flattening intersected types</caption>
*
* ```ts
* import { expectTypeOf } from 'expect-type'
*
* type PositionProps = {
* top: number
* left: number
* }
*
* type SizeProps = {
* width: number
* height: number
* }
*
* expectTypeOf<PositionProps & SizeProps>().not.toEqualTypeOf<{
* top: number
* left: number
* width: number
* height: number
* }>()
*
* expectTypeOf<Simplify<PositionProps & SizeProps>>().toEqualTypeOf<{
* top: number
* left: number
* width: number
* height: number
* }>()
* ```
*
* @since 1.0.0
* @internal
* @see {@link https://github.com/sindresorhus/type-fest/blob/main/source/simplify.d.ts | Source}
*/
type Simplify<TypeToFlatten> = TypeToFlatten extends AnyFunction
? TypeToFlatten
: {
[KeyType in keyof TypeToFlatten]: TypeToFlatten[KeyType]
} & AnyNonNullishValue

/**
* A utility type that makes specific properties of a given type `readonly`.
* It takes two type parameters: {@linkcode BaseType | the base type} and
* {@linkcode KeysToBecomeReadonly | the keys of the properties}
* that should be made `readonly`. The properties specified by the
* {@linkcode KeysToBecomeReadonly | keys} parameter will become
* `readonly`, while the rest of the type remains unchanged.
*
* @example
* <caption>#### Set specific properties to `readonly`</caption>
*
* ```ts
* import { expectTypeOf } from 'expect-type'
*
* type Post = {
* author: string
* content: string
* title: string
* }
*
* expectTypeOf<SetReadonly<Post, 'title' | 'author'>>().toEqualTypeOf<{
* readonly author: string
* content: string
* readonly title: string
* }>()
* ```
*
* @template BaseType - The base type whose properties will be transformed to `readonly`.
* @template KeysToBecomeReadonly - The keys of the __`BaseType`__ to be made `readonly`.
*
* @since 1.0.0
*/
export type SetReadonly<BaseType, KeysToBecomeReadonly extends keyof BaseType> = BaseType extends unknown
? Simplify<Omit<BaseType, KeysToBecomeReadonly> & Readonly<Pick<BaseType, KeysToBecomeReadonly>>>
: never
12 changes: 12 additions & 0 deletions test/usage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,18 @@ test('Use `.omit` to remove a set of properties from an object', () => {
expectTypeOf<Person>().omit<'name'>().toEqualTypeOf<{age: number}>()
})

test('Use `.readonly` to create a `readonly` version of a type', () => {
type Post = {title: string; content: string}

expectTypeOf<Post>().readonly().toEqualTypeOf<Readonly<Post>>()
})

test('`.readonly` can make specific properties `readonly`', () => {
type Post = {title: string; content: string}

expectTypeOf<Post>().readonly('title').toEqualTypeOf<{readonly title: string; content: string}>()
})

test('Make assertions about object properties', () => {
const obj = {a: 1, b: ''}

Expand Down