microsoft / microsoft/TypeScript

strictFunctionTypes prevents an assignment not related to functions

Open
#28,671 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.3.0-dev.20181122

Search Terms:
covariance, contravariance, keyof, interface, class, generic

Code

interface IBase {
    foo: string;
}

interface IDerived extends IBase {
    bar: string;
}

type StringPropertyNames<T> = { [P in keyof T]: T[P] extends string ? P : never }[keyof T]
type StringProperties<T> = Pick<T, StringPropertyNames<T>>

interface Foo<T> {
    readonly Bar: StringProperties<T>;
}

let baseProperties: StringProperties<IBase>
let derivedProperties: StringProperties<IDerived>

let baseInterface: Foo<IBase>
let derivedInterface: Foo<IDerived>

baseProperties = derivedProperties // no error
baseInterface = derivedInterface

tsc test.ts --strictFunctionTypes

Expected behavior:
Compiles without errors.

Actual behavior:

test.ts:23:1 - error TS2322: Type 'Foo<IDerived>' is not assignable to type 'Foo<IBase>'.
  Property 'bar' is missing in type 'IBase' but required in type 'IDerived'.

23 baseInterface = derivedInterface
   ~~~~~~~~~~~~~

  test.ts:6:5
    6     bar: string;
          ~~~
    'bar' is declared here.

Playground Link:

Related Issues:
#24190

The documentation says:

Under --strictFunctionTypes function type parameter positions are checked contravariantly instead of bivariantly.

I couldn't find any information saying it should affect anything else.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the supplied example in test.ts with tsc test.ts --strictFunctionTypes, and compare the two assignment results. The payload names no implementation file or regression test, so trace the type-checking path for the reported generic mapped-type assignment. Done means the reported assignment behavior matches the expected result without regressing strict function parameter checking.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
28/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.