定义在typescript中作为参数传递的对象的参数类型,而不知道参数的名称

时间:2017-01-13 12:54:48

标签: typescript

我有一个需要对象作为参数的函数。 此对象的所有参数都应遵循接口定义的规则。我该如何定义?

示例代码:

export default class Comp1 extends React.Component {

    constructor(props) {
        super(props);
    }
    render() {
        return (
            <form onSubmit={this.handleSubmit.bind(this)}>
    <input type = "text"
        placeholder = "Start Typing"
        value = {this.props.searchTerm}
        onChange = {this.handleChange.bind(this, 'searchTerm')} />
    <input type="submit" value="Submit"/>
            </form>
    );
    }
}

class Comp2 extends React.Component {

    render() {
        return (
            <div>
            {this.props.info.text}
    </div>
    );
    }
}

所以interface Fruit { color: string; weight: number; } function printFruits(fruits) { for (fruit in fruits) { print(fruit + ' is ' + fruits[fruit].color) } } 参数就是这样的:

fruits

1 个答案:

答案 0 :(得分:1)

类型是:

function printFruits(fruits: { [name: string]: Fruit }) {
   for (fruit in fruits) {
      print(fruit + ' is ' + fruits[fruit].color)
   }
}

您还可以为其设置类型别名:

type Fruits = { [name: string]: Fruit };

function printFruits(fruits: Fruits) {
   for (fruit in fruits) {
      print(fruit + ' is ' + fruits[fruit].color)
   }
}