简体   繁体   English

Typescript 父接口属性默认值

[英]Typescript default value of parent interface property

interface Iparent {
  a: string
}
interface Ichild extends parent {
a: '';
}
const x: child = {}

This throws a compiler error when using child How to provide a default value for a in child interface?使用子接口时会引发编译器错误如何a子接口提供默认值?

Edit:编辑:

Class parent actually looks like this: Class 父级实际上如下所示:

class parent extends React.Component<Iparent> {}

class child extends React.Component<Ichild> {}

parent class should have a prop but child class should just have a default value for it ie ''父 class 应该有一个道具,但子 class 应该只有一个默认值,即''

There are a few mistakes:有几个错误:

  1. a: '' not do default value, it means that a can be only '' it is like animal: 'dog' | 'cat' a: ''不做默认值,表示a只能是''就像animal: 'dog' | 'cat' animal: 'dog' | 'cat' may be only 'dog' or 'cat' value. animal: 'dog' | 'cat'可能只有'dog''cat'值。
  2. Interfaces have no default values - they are used like less specified types.接口没有默认值——它们被用作较少指定的类型。 If you want have default value you should use class child:如果你想有默认值,你应该使用 class 孩子:
class child implements parent{
    a = '';
}
const x: child = new child();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM