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

TS中any和unknown类型区别 #134

Open
GGXXMM opened this issue Apr 14, 2023 · 0 comments
Open

TS中any和unknown类型区别 #134

GGXXMM opened this issue Apr 14, 2023 · 0 comments

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Apr 14, 2023

定义及其区别

  • any 任意类型,用来表示赋值允许任意值,跳过类型检查
  • unknown 未知类型,和 any 的主要区别是 unknown 类型会更加严格,在对unknown类型的值在缩小未知范围前,不能进行任何操作比如实例化、getter、函数执行等。
function getDogName() {
    let x: unknown;
    return x;
};
const dogName = getDogName();
// const upName = dogName.toLowerCase(); // Error
/** 缩小范围 */
// typeof
if (typeof dogName === 'string') {
    const upName = dogName.toLowerCase(); // OK
}
// 类型断言
const upName = (dogName as string).toLowerCase(); // OK
@GGXXMM GGXXMM changed the title TS中any、unknown与never类型区别 TS中any和unknown类型区别 Apr 14, 2023
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