账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    【TS】自己通过type 声明的类型别名,在类型推断中不起作用
    57
    0

    请看代码:

    interface Animal {
        typ: string;
    }
    class Duck implements Animal {
        typ: string = "鸭子"
    }
    class Goose implements Animal {
        typ: string = "鹅"
    }
    class Fish implements Animal {
        typ: string = "鱼"
    }
    
    // 鸭子和鹅可以飞,但是鱼不行
    type canFly = (Duck | Goose);
    
    // 必须是可以飞的动物
    function fly(animal: canFly): void {
        console.log(animal.typ + '飞走了');
    }
    
    let duck = new Duck();
    fly(duck);
    
    let goose = new Goose();
    fly(goose);
    
    // 不知道为什么期待的报错没有出现
    let fish: Fish = new Fish();
    fly(fish);
    

    求大神解答

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    • ✎﹏ℳ๓初染♡ 普通会员 1楼

      在TypeScript中,可以通过一些方式来推断类型别名在类型推断中不起作用。具体来说,可以使用TypeAnnotation关键字来在类型注解中指定类型别名。

      以下是一个例子:

      ```typescript interface Animal { name: string; age: number; }

      interface Person extends Animal { address: string; }

      const person: Person = { name: 'John Doe', age: 30, address: '123 Main St' };

      console.log(person.name); // 输出:John Doe console.log(person.age); // 输出:30 console.log(person.address); // 输出:123 Main St ```

      在这个例子中,我们定义了两个接口AnimalPerson。在类型注解中,我们为Person接口指定了一个类型别名address

      然后,我们创建了一个Person对象,并将nameage属性的值赋给了它。接着,我们使用console.log来打印出person对象的属性值。由于我们没有在person对象上使用address类型的别名,所以console.log会直接打印出address的值,而不是它作为Person接口的别名。

      注意,TypeAnnotation关键字通常用于类型注解,而不是类型推断。类型推断是TypeScript的一种特性,它允许开发者通过编译器自动推断类型。如果你的类型推断在运行时出现问题,你可以检查你的代码,确保所有的类型别名都被正确地引用。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部