#Please help me understand typing behavior

1 messages · Page 1 of 1 (latest)

raven jungle
#
import type {User, CustomFilter} from '../app'

const sort = (data: User[], filters: CustomFilter): User[] => {

  if(filters.length === 0) return data

  return data.sort((a,b)=> {
    for(const filter of filters){
      const {key, value} = filter;

      if (value === 'ASC') {
        if (a[key] < b[key]) return -1;
        if (a[key] > b[key]) return 1;
      } else if (value === 'DESC') {
        if (a[key] > b[key]) return -1;
        if (a[key] < b[key]) return 1;
      }
    }

    return 0;
  });
}

const settings: ['ASC', 'DESC'] = ['ASC', 'DESC']

sort.settings = settings;

console.log(sort.settings); // work

type CustomSortFunction = (data: User[], filters: CustomFilter) => User[];

type Sorts = {
  [SortFunctionName: string]: CustomSortFunction;
}

const sorts: Sorts = { sort };

console.log(sorts.sort.settings); // Don't see property "settings"
console.log(sorts.settings); // Property "settings" is available. I don't really understand why

Why am I getting an error at the line console.log(sorts.sort.settings); . But there is no error in the line console.log(sorts.settings);.

agile crow
#

hover over sorts.settings to see its actual type

raven jungle
agile crow
bitter bear
#

to answer the inverse question (why sorts.settings is available), a type that looks like this:

type Foo = { [x: string]: Bar }

has what's called an "index signature" (that's the part between [ and ]). what this type says is that you can index into of type Foo using any string and expect to get back a Bar. that's what -n- meant when they said "sorts accepts any string as a key"

#

"settings" isn't special in your original code. you can also do sorts.blah or sorts["some arbitrary string"] or even sorts["😂"] and see the same behavior. at runtime those will all give you back undefined (and if you enable the noUncheckedIndexedAccess compiler option then the type system will reflect this)

raven jungle
rotund prawn
#