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

辨析联合类型和引用的问题 #154

Open
wqcstrong opened this issue Dec 20, 2019 · 0 comments
Open

辨析联合类型和引用的问题 #154

wqcstrong opened this issue Dec 20, 2019 · 0 comments

Comments

@wqcstrong
Copy link
Contributor

正常情况下:

interface Square {
    kind: 'square';
    size: number;
}

interface Rectangle {
    kind: 'rectangle';
    width: number;
    height: number;
}

type Shape = Square | Rectangle;

function size(s: Shape) {
    // 基于 联合类型 和 kind 特殊字面量
    // 如果我们用了判断语句,ts会自动帮我们缩小类型范围
    if (s.kind === 'square') {
        return s.size * s.size
    }
    // 这里ts推断出 s 是 Rectangle
    return s.width * s.height
}

不符合预期的一种情况:

interface Square {
    kind: 'square';
    size: number;
}

interface Rectangle {
    kind: 'rectangle';
    width: number;
    height: number;
}

type Graph = {
    [key: string]: Square | Rectangle
}

function size(s: Graph, key: string) {
    if (s[key].kind === 'square') {
        return s[key].size * s[key].size // Error
    }
    return s[key].width * s[key].height // Error
}

对于不符合逾期的情况有点不解,为什么ts对于这种情况推断不出来呢?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant