DanielXMoore / Civet

A TypeScript superset that favors more types and less typing
https://civet.dev
MIT License
1.36k stars 29 forks source link

`satisfies` for type definitions #271

Open edemaine opened 1 year ago

edemaine commented 1 year ago

Oren suggests this useful syntax for asserting one type satisfies another:

type T = ... satisfies U
↓↓↓
type T = ...
null as any as T satisfies U

And maybe by extension:

interface T satisfies U ...
↓↓↓
interface T ...
null as any as T satisfies U

More generally we could imagine supporting T satisfies U anywhere, but then we'd need to know that T is a type not a value, which is maybe not possible in general. It's probably most important to support at type definitions anyway, hence the above syntax proposals.

Or perhaps this feature in type declarations should be called implements, with <: shorthand, as classes already support exactly this under that name. See https://github.com/Microsoft/TypeScript/issues/24274

Somewhat related, maybe this could be useful:

function f(x, y) satisfies T
  ...
SonahtQ commented 1 year ago

Another use case:

export interface Action {
    //...
}

export interface Actions {
    [key: string]: Action
}

//

export interface ExampleActions extends Actions {
    testAction: {
        // ...
    }

    testAction2: {
        // ...
    }
}

type ActionNames_Of_ExampleActions = keyof ExampleActions;

const exampleActionName: ActionNames_Of_ExampleActions = "gfhgfh";

Some could expect that ActionNames_Of_ExampleActions is "testAction" | "testAction2" but it isn't, it is string because of super Actions interface.

But with satisfies keyword, that could be possible:

export interface Action {
    //...
}

export interface Actions {
    [key: string]: Action
}

//

export interface ExampleActions satisfies Actions {
    testAction: {
        // ...
    }

    testAction2: {
        // ...
    }
}

type ActionNames_Of_ExampleActions = keyof ExampleActions;

const exampleActionName: ActionNames_Of_ExampleActions = "gfhgfh"; //error, not allowed