Enforcing distinct number of trailing spaces

I wouldn't call this a good solution but it seems to work. You can create a computed column with an appended character and create a unique index on code_type and the computed column. For the appended character you can use a character which will never appear in your data or any string of at least 31 character length if you'd like to avoid making assumptions like that. It's probably easiest to go through an example.

This is the problem that you're having:

CREATE TABLE dbo.T226714 (
    code_type CHAR(4) NOT NULL,
    code VARCHAR(30) NOT NULL,
    PRIMARY KEY (code_type, code)
);

-- fails due to PK error
INSERT INTO dbo.T226714 VALUES ('cha', ' ');
INSERT INTO dbo.T226714 VALUES ('cha', '');

Instead, do something like this:

DROP TABLE dbo.T226714;

CREATE TABLE dbo.T226714 (
    code_type CHAR(4) NOT NULL,
    code VARCHAR(30) NOT NULL,
    code_with_end_char AS CAST(code + 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ' AS VARCHAR(61))
);

CREATE UNIQUE INDEX UI ON dbo.T226714 (code_type, code_with_end_char);

-- works
INSERT INTO dbo.T226714 VALUES ('cha', ' ');
INSERT INTO dbo.T226714 VALUES ('cha', '');

-- can't insert this as a third row due to the unique index:
INSERT INTO dbo.T226714 VALUES ('cha', ' ');

Another idea, similar to Joe Obbish's answer. It, too, requires that the code be defined as VARCHAR.

It calculates the length of the string using either LEN(code + 'X') or more simply DATALENGTH(code) (thnx to @PaulWhite):

CREATE TABLE T226714 (
    code_type CHAR(4) NOT NULL,
    code VARCHAR(30) NOT NULL,
    -- code_len AS len(code + 'X') - 1
    code_len AS datalength(code) 
);

CREATE UNIQUE INDEX UI ON T226714 (code_type, code, code_len);
GO
-- works
INSERT INTO T226714 VALUES ('cha', ' ');
INSERT INTO T226714 VALUES ('cha', '');
GO
2 rows affected
-- can't insert this as a third row due to the unique index:
INSERT INTO T226714 VALUES ('cha', ' ');
GO
Msg 2601 Level 14 State 1 Line 2
Cannot insert duplicate key row in object 'dbo.T226714' 
with unique index 'UI'. The duplicate key value is (cha ,  , 1).
Msg 3621 Level 0 State 0 Line 2
The statement has been terminated.
-- can't insert this as a third row due to the unique index:
INSERT INTO T226714 VALUES ('cha', '');
GO
Msg 2601 Level 14 State 1 Line 2
Cannot insert duplicate key row in object 'dbo.T226714' 
with unique index 'UI'. The duplicate key value is (cha , , 0).
Msg 3621 Level 0 State 0 Line 2
The statement has been terminated.
select * from T226714 ;
GO
code_type | code | code_len
:-------- | :--- | -------:
cha       |      |        0
cha       |      |        1

db<>fiddle here