#Is this a bug with template string keys?

9 messages · Page 1 of 1 (latest)

tiny fernBOT
#
mbarvian#0

Preview:```ts
type CustomProperties = {
[property: --${string}]: string
}

function test(fn: () => CustomProperties) {}

test(() => ({
// I want this to fail for missing the -- prefix:
test: "1px",
}))```

tight meadow
#

@next rose This is an 'excess keys' issue - TS allows excess keys on objects, in general, including on inferred return signatures

#

I think what's going on is CustomProperties essentially doesn't have any required properties (it's basically a variant on Record<string, string>).

#

The callback infers as () => { test: string } and { test: string } is assignable to CustomProperties.

#

e.g. it's basically like this:

#
type CustomProperties = { [property: `--${string}`]: string }

const x = { test: "1px" };
const y: CustomProperties = x;
#

TS does sometimes warn about excess properties - e.g. if you do const x: CustomProperties = { test: "1px" }, but that's more of a lint rule than a hard rule of the type system.

#

One place it does warn is explicit return types, so if you do this, you get an error:

tiny fernBOT
#
type CustomProperties = { [property: `--${string}`]: string }

function test(fn: () => CustomProperties) {}

test((): CustomProperties => ({
    'test': '1px'
//  ^^^^^^
// Object literal may only specify known properties, and ''test'' does not exist in type 'CustomProperties'.
}))