Microsoft/TypeScript

Unhelpful TS2322 error message when assigning a type to another type.

Open

#50.114 aberto em 31 de jul. de 2022

Ver no GitHub
 (2 comments) (1 reaction) (0 assignees)TypeScript (6.726 forks)batch import
BugDomain: Error MessagesHelp Wanted

Métricas do repositório

Stars
 (48.455 stars)
Métricas de merge de PR
 (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)

Description

Bug Report

🔎 Search Terms

TS2322 unhelpful message

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about TS2322

⏯ Playground Link

Playground link with relevant code

💻 Code

type StringMap = {
	[x: string]: string;
}

type Message<TMap extends StringMap, T extends keyof TMap> = {
	bar: "bar";
	type: T;
}

type MessageHelper<TMap extends StringMap, T extends keyof TMap> =
	T extends keyof TMap ?
		Message<TMap, T> :
		never;

function foo<TMap extends StringMap, T extends keyof TMap>(type: T) {
	const message : Message<TMap, T> = {
		bar: "bar",
		type,
	}

	const message2 : MessageHelper<TMap, T> = message;
	//    ^^^^^^^^------- Type 'Message<TMap, T>' is not assignable to type 'MessageHelper<TMap, T>'.

	message.type; // T extends keyof TMap
	message2.type; // (keyof TMap & string) | (keyof TMap & number) | (keyof TMap & symbol)

	message.type = message2.type;
	// ^^^^^^^^^ This is more helpful, but I had to jump through quite some hoops to finally figure
	// out this was the cause.
}


🙁 Actual behavior

The error that occurs when assigning message to message2 shows just

Type 'Message<TMap, T>' is not assignable to type 'MessageHelper<TMap, T>'.

🙂 Expected behavior

A better explanation of why the types are not assignable. I'm assuming it's because the types of message.type are different. But this isn't clearly shown in the error message.

Guia do colaborador