ngrx select 字符串是什么类型?

ngrx select strings are types?

我想说我在 Typescript 和 Angular(包括 ngrx)方面都处于初学者水平。

我正在努力思考 select Store class 的方法可以接受字符串文字作为参数。这是代码:

export interface AppState {
    readonly tutorial: Tutorial[];
}

export class ReadComponent {

  constructor(private store: Store<AppState>) {
    this.tutorials = store.select('tutorial');
  }
}

现在,我看到 AppState class 有一个教程 属性,这似乎就是所谓的 store.select( 'tutorial') 是为了,但如何呢?如果我将传递给 select ex 的文字更改为怎么回事? store.select('yadayada'),编译器报错Argument of type '"yadayada"' is not assignable to parameter of type '"tutorial"'. "tutorial" 和 "yadayada" 类型如何?为什么编译器将字符串文字作为类型?

它将其推断为存储对象类型的键,并可以从中推断出值类型。例如,您可以定义一个通用函数:

const getKey = <T>(obj: T, key: keyof T) => obj[key] ;

如果 key 不是 T 的键,它将正确推断 return 类型并给出编译器错误。您可以将函数的 return 值显式键入为 T[keyof T] . Typescript 泛型和类型推断非常强大。