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

Generic type narrowing by typeof #23

Open
fuafa opened this issue Sep 5, 2019 · 0 comments
Open

Generic type narrowing by typeof #23

fuafa opened this issue Sep 5, 2019 · 0 comments
Labels
note a peace of knowledge typescript

Comments

@fuafa
Copy link
Owner

fuafa commented Sep 5, 2019

type IsString<X> = [X] extends [string] ? true : false

function isString<X extends string, Y>(x: X, y: Y)  {
    if (typeof x === "string") {
		// 因为 typeof x === 'string' 并没有为 X 增加额外的信息 (X 本来就 extends string)
		x; // X extends string,
        const a: IsString<typeof x> = true; // error: conditional type is deferred
    }
    if (typeof y === "string") {
		// 1. Y 原来并没有任何约束, (no extends)
		// 2. typeof y === 'string' -> typeof y <: string, 
		// 3. 同时 y: Y, 
		// 4. 所以 typeof y <: Y & string
		y; // Y & string,
        const b: IsString<typeof y> = true;
    }
}

microsoft/TypeScript#29939 (comment)

@fuafa fuafa added note a peace of knowledge typescript labels Sep 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
note a peace of knowledge typescript
Projects
None yet
Development

No branches or pull requests

1 participant